为什么这个Ruby条件赋值没有被记忆?
有人能解释一下为什么这个规范失败了吗 RSpec结果:为什么这个Ruby条件赋值没有被记忆?,ruby,rspec,Ruby,Rspec,有人能解释一下为什么这个规范失败了吗 RSpec结果: User#presenter memoizes presenter Failure/Error: user.presenter (<UserPresenter (class)>).new(...) expected: 1 time with any arguments received: 2 times with arguments: (...) 问题在于这一
User#presenter memoizes presenter
Failure/Error: user.presenter
(<UserPresenter (class)>).new(...)
expected: 1 time with any arguments
received: 2 times with arguments: (...)
问题在于这一行:
UserPresenter.should_receive(:new).once
这段代码只是建立了一个期望,即UserPresenter
将一次性接收new
方法。它删除了原始的UserPresenter#新的
方法,并将其替换为返回nil
的方法。由于nil
是错误的,因此@presenter
实例变量不会被记忆
要解决此问题,可以在期望值中指定返回值:
UserPresenter.should_receive(:new).once.and_return "some truthy value"
或同等地
UserPresenter.should_receive(:new).once { "some truthy value" }
或者如果您确实想调用原始方法
UserPresenter.should_receive(:new).once.and_call_original
或者使用新的expect语法
expect(UserPresenter).to receive(:new).once.and_call_original
有关预期消息的更多信息,以及有关调用原始方法的更多信息,请参阅。对RSpec的
应该接收方法进行了进一步的讨论。为什么不UserPresenter.should\u receive(:new)。once.with(…)
?@ArupRakshit不会更改任何接收的内容:使用参数调用了2次…
,尽管测试是否使用正确的参数调用它可能是一个好主意。你能做到让我来!(:user){build_stubbed(:user)}
和UserPresenter.should_receive(:new)。once.with(user)
?失败/错误:user.presenter()。新(#)预期:1次带参数:(#)收到:2次带参数:(#)请加入-
expect(UserPresenter).to receive(:new).once.and_call_original