我最近将一个 Ruby on Rails 项目从 rspec-core / rspec-rails 2.10.1 升级到 2.14。现在(正如我担心的那样)很多测试都失败了,但这只是因为一些方法已经改变。我已经修复了弃用(存根!->存根,模拟->双),但还有更多。我在任何地方都使用的一种重要方法是我在这里找到的:https ://www.ruby-forum.com/topic/126993到存根关联方法:
module RSpec
module Mocks
module Mock
def stub_association!(association_name, methods_to_be_stubbed = {})
mock_association = RSpec::Mocks::Mock.new(association_name.to_s)
methods_to_be_stubbed.each do |method, return_value|
mock_association.stub(method).and_return(return_value)
end
self.stub(association_name).and_return(mock_association)
end
end
end
end
现在这会引发以下错误消息:
Failure/Error: @foo.stub_association!(:children, :sorted => [])
Double "Foo_1910" received unexpected message :stub_association! with (:children, {:sorted=>[]})
我希望上面的模块名称已经改变,但我无法弄清楚到底是什么。任何提示将不胜感激。
其次,我使用这样的代码来存根控制器方法:
112) ApplicationHelper admin_link_to not logged in: should output nothing
Failure/Error: stub(:authenticate_with_http_basic).and_return nil
Stub :authenticate_with_http_basic received unexpected message :and_return with (nil)
控制器方法在哪里
def admin_link_to(...)
return link_to(...) if logged_in? and current_user.has_role?(:admin)
end
并logged_in?
调用authenticate_with_http_basic do |login, password| ...
。同样,我曾经存根request
为正在测试的控制器或助手提供虚假请求对象。
如何在 rspec-rails 2.14 中执行此操作?
更新
似乎除了重命名Mock
为TestDouble
(stub_association!
需要上面的调用)之外,我只需要在我的调用之前放置controller
或放置,具体取决于正在测试的内容。所以helper
stub(...)
stub(:authenticate_with_http_basic).and_return nil
变成
helper.stub(:authenticate_with_http_basic).and_return nil
在大多数情况下,这可以正常工作。重命名Mock
为TestDouble
只是蛋糕的一半 - 我仍然不能stub_association!
在真实对象上使用我的方法,只能在模拟(或双打,因为它们现在被称为)。
所以我80%在那里。最后20%有人涨吗?:)