【问题标题】:How to mock a method call in Rspec如何在 Rspec 中模拟方法调用
【发布时间】:2013-09-11 19:31:19
【问题描述】:

我对 TDD 和 Rspec 还很陌生。我试图弄清楚如何确保在测试中调用了一个方法:

module Authentication
  include WebRequest

  def refresh_auth_token(refresh_token)
    "refreshing token"
  end
end


class YouTube
  include Authentication
  attr_accessor :uid, :token, :refresh

  def initialize(uid, token, refresh)
    @uid = uid
    @token = token
    @refresh = refresh

    # if token has expired, get new token
    if @token == nil and @refresh
      @token = refresh_auth_token @refresh
    end
  end

end

这是我的测试:

$f = YAML.load_file("fixtures.yaml")

describe YouTube do
  data = $f["YouTube"]
  subject { YouTube.new(data["uid"], data["token"], data["refresh"]) }
  its(:token) { should == data["token"] }

  context "when token is nil" do
    subject(:without_token) { YouTube.new(data["uid"], nil, data["refresh"]) }
    its(:token) { should_not be_nil }
    it { YouTube.should_receive(:refresh_auth_token).with(data["refresh"]) }
  end

end

但它失败了:

) 令牌为零时的 YouTube 失败/错误:它 { YouTube.should_receive(:refresh_auth_token).with(data["refresh"]) } ().refresh_auth_token("1/HBTNQ93otm1cSQH8kKauij3jO0kZQYfgH5J-hBtAP8k") 预期:1 次带参数:(“1/HBTNQ93otm1cSQH8kKauij3jO0kZQYfgH5J-hBtAP8k”) 收到:0 次带参数:(“1/HBTNQ93otm1cSQH8kKauij3jO0kZQYfgH5J-hBtAP8k”) # ./lib/youtube/you_tube_test.rb:14:in `block (3 levels) in '

我在此测试中尝试做的是确定@token 何时为零,并且提供了@refresh,如果在initialize 上调用refresh_auth_token。这个 mocks 和 stubs 有点令人困惑。

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    首先,你要使用any_instance

    YouTube.any_instance.should_receive(:refresh_auth_token).with(data["refresh"])
    

    目前,您正在检查是否正在调用类方法refresh_auth_token。不是,因为它不存在。

    接下来,当代码在构造函数中执行时,该行不会捕获调用,因为对象已经在规范之前的主题行中创建。

    这是最简单的解决方案:

      context "when token is nil" do
        it "refreshed the authentation token" do
            YouTube.any_instance.should_receive(:refresh_auth_token).with(data["refresh"]) 
            YouTube.new(data["uid"], nil, data["refresh"]) 
        end
      end
    

    【讨论】:

    • 谢谢,any_instance 成功了。我曾想过在should_receive 之后再次致电YouTube.new,但没有成功。现在可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    相关资源
    最近更新 更多