1

我对 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提供的,如果refresh_auth_token被调用initialize。这个模拟和存根的事情有点令人困惑。

4

1 回答 1

3

首先,您要使用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
于 2013-09-08T00:32:15.787 回答