我的测试中有这个
Project.should_receive(:find).with(@project).and_return(@project)
Run Code Online (Sandbox Code Playgroud)
但是当对象接收到该方法调用两次时,我必须这样做
Project.should_receive(:find).with(@project).and_return(@project)
Project.should_receive(:find).with(@project).and_return(@project)
Run Code Online (Sandbox Code Playgroud)
有什么方法可以说出类似的话
Project.should_receive(:find).with(@project).and_return(@project).times(2)
Run Code Online (Sandbox Code Playgroud) 已经有类似的问题,但它们都会覆盖返回值,nil除非.and_return被调用
问题
我想知道是否有办法只检查一个方法是否被调用使用expect_any_instance_of(Object).to receive(:somemethod)并且它正常运行而不会覆盖或影响返回值.somemethod.
考虑以下:
# rspec
it 'gets associated user' do
expect_any_instance_of(Post).to receive(:get_associated_user)
Manager.run_processes
end
# manager.rb
class Manager
def self.run_processes
associated_user = Category.first.posts.first.get_associated_user
associated_user.destroy!
end
end
Run Code Online (Sandbox Code Playgroud)
上面的规范虽然会起作用,因为它:get_associated_user被称为run_processes,但它NoMethodError: undefined method 'destroy!' for NilClass正好引起,因为我嘲笑了:get_associated_userPost的任何实例.
我可以添加一个.and_return方法,expect_any_instance_of(Post).to receive(:get_associated_user).and_return(User.first)以便它可以工作而不会引发该错误,但这已经是一个模拟的返回值(可能会影响它下面的其余代码),而不是它应该在当时返回的正确的期望值该方法被调用.
但是.and_return(correct_user) ,我可以指定correct_user用户在哪里将返回相同的返回值,就好像它已正常运行一样.但是,这需要我模拟序列中的每个返回值,Category.first.posts.first.get_associated_user以便它能正常工作.实际问题比上面复杂得多,因此在我的情况下,存根不是真正可行的解决方案.