【发布时间】:2013-02-13 00:12:19
【问题描述】:
使用 Mocha,我正在对需要返回 2 个单独值的相同方法进行存根。无论我做什么,它只返回 2 个值中的 1 个,因此我的 rspec 测试中的 1 个总是失败。如何让存根在正确的时间返回正确的值?
代码:
describe "#method" do
it "has something" do
hash = { "allow_sharing" => "1"}
CustomClass.stubs(:app_settings).returns(hash)
get 'method', :format => :json
JSON.parse(response.body).count.should eq(1)
end
it "does not have something" do
hash = { "allow_sharing" => "0"}
CustomClass.stubs(:app_settings).returns(hash)
get 'method', :format => :json
JSON.parse(response.body).count.should eq(0)
end
end
我也用before 块尝试过这种方式。还是没有运气。
describe "#method" do
before do
hash = { "allow_sharing" => "1"}
CustomClass.stubs(:app_settings).returns(hash)
end
it "has something" do
get 'method', :format => :json
JSON.parse(response.body).count.should eq(1)
end
# ... etc.
【问题讨论】:
-
您是否尝试在存根后立即调用
CustomClass.app_settings以验证它是否返回了预期的哈希值?这可能有助于缩小问题范围,并消除对其他原因导致您的响应出现意外计数的任何疑问。 -
an4rcho,你的建议成功了。存根工作正常。问题出在
get 'method'本身。它没有正确检查值。
标签: ruby ruby-on-rails-3 rspec ruby-mocha