Mocha:如何设置对实例方法的期望?
假设这个 ruby 代码:
class User
def self.failed_login!(email)
user = User.find_by_email(email)
if user
user.failed_login_count = user.failed_login_count + 1
user.save
end
end
end
我想编写一个测试来测试当给出无效电子邮件时永远不会调用 user.save 。 例如:
it "should not increment failed login count" do
User.expects(:save).never()
User.failed_login!("doesnotexist")
end
此测试当前通过,但当我提供有效的电子邮件地址时它也会通过。
如何使用 Mocha 设置期望? (或任何其他模拟框架),以便它测试任何 User 实例的 save 方法永远不会被调用?
(最好不要存根/模拟 find_by_email 方法,因为如何获取用户的实现将来可能会改变)
干杯
Assume this ruby code:
class User
def self.failed_login!(email)
user = User.find_by_email(email)
if user
user.failed_login_count = user.failed_login_count + 1
user.save
end
end
end
I want to write a test that tests that user.save is never called when an invalid email is given. E.g.:
it "should not increment failed login count" do
User.expects(:save).never()
User.failed_login!("doesnotexist")
end
This test currently passes, but it also passes when I provide a valid email address.
How do I set up the expectation using Mocha? (or any other mocking framework) such that it tests the save method of any User instance is never called?
(preferably without stubbing/mocking the find_by_email method, as the implementation of how to get the user might change in the future)
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者你可以做类似的事情
alternatively you could do something like
对于其他可能偶然发现这一点的人,我在另一篇文章中找到了答案,该文章将 RR 作为模拟框架......在 Mocha 中你可以这样做:
For others that might have stumbled unto this, I found the answer in another post that was dealing with RR as the mocking framework... in Mocha you can do this: