RSpec:如何创建辅助存根方法? [英] RSpec: How to create a helper stub method?

查看:35
本文介绍了RSpec:如何创建辅助存根方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的助手中存根一个助手方法:

I am trying to stub a helper method from my helper:

# sessions_helper.rb
require 'rest_client'

module SessionsHelper
  BASE_URL = "http://localhost:1234"

  def current_user?(token)
    sessions_url = BASE_URL + "/sessions"
    headers = {"X-AuthToken" => 12345}

    begin
      RestClient.get(sessions_url, headers)
      return true
    rescue RestClient::BadRequest
      return false
    end
  end

end

我尝试存根 current_user?在我的单元测试中始终返回 true:

I try to stub the current_user? to always return true in my unit test:

require 'spec_helper'

describe SessionsHelper do
  it "Should not get current user with random token" do
    SessionsHelper.stub(:current_user?).and_return(true)
    expect(current_user?(12345)).to eq(false)
  end
end

但测试仍然通过(我希望它返回 true).

But the test still pass (I expect it returns true instead).

在配置存根方法时有什么我想念的吗?

Is there something I miss to configure the stub method?

谢谢

推荐答案

any_instance 应该做你想做的:

SessionsHelper.any_instance.stub(:current_user?).and_return(true)

正如@Vimsha 所说,您在模块和实例之间混淆了,这很容易做到.

As @Vimsha says, you got confused between the module and the instance, which is easy to do.

这篇关于RSpec:如何创建辅助存根方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆