Ruby on rails RSpec Mocking Mailer——第二次调用时失败
我正在测试一些涉及电子邮件的方法,并尝试使用模拟邮件对象。很明显,我的做法是错误的,因为第一次测试是有效的,但随后同样的测试失败了。如果有人能解释一下这里发生了什么,我将不胜感激。谢谢Ruby on rails RSpec Mocking Mailer——第二次调用时失败,ruby-on-rails,rspec,mocking,actionmailer,Ruby On Rails,Rspec,Mocking,Actionmailer,我正在测试一些涉及电子邮件的方法,并尝试使用模拟邮件对象。很明显,我的做法是错误的,因为第一次测试是有效的,但随后同样的测试失败了。如果有人能解释一下这里发生了什么,我将不胜感激。谢谢 describe SentMessage do before(:each) do Notifier ||= mock('Notifier', :send_generic => true) end it "Sends an email" do Notifier.sh
describe SentMessage do
before(:each) do
Notifier ||= mock('Notifier', :send_generic => true)
end
it "Sends an email" do
Notifier.should_receive(:send_generic).with(['a@contact.com'], 'test')
Notifier.send_generic(['a@contact.com'], 'test').should_not be_nil
end
it "Sends an email" do
Notifier.should_receive(:send_generic).with(['a@contact.com'], 'test')
Notifier.send_generic(['a@contact.com'], 'test').should_not be_nil
end
end
结果:
Failures:
1) SentMessage Sends an email
Failure/Error: Notifier.send_generic(['a@contact.com'], 'test').should_not be_nil
expected: not nil
got: nil
# ./spec/models/test.rb:14:in `block (2 levels) in <top (required)>'
故障:
1) SentMessage发送电子邮件
失败/错误:通知程序。发送\u通用(['a@contact.com“],”test')。不应为空
预期:不是零
得:零
#./规格/型号/测试.rb:14:in‘分块(2级)’in’
Rspec为模拟和预期插入设置/拆卸内容。这样做的目的是验证是否满足了应收到的期望值,并清除对象中设置的超出单个规范的模拟。例如,如果您在一个规范中设置了存根User.find,您就不会期望该存根存在于另一个规范中
因此,在第一个规范的末尾,rspec将在每个规范之前删除中的存根设置。因为您正在执行| |=,所以不会重新创建通知程序,存根也不会。这反过来意味着,当您在第二个规范中调用should_receive时,您正在设置一个新的存根。因为这个新存根没有指定的返回值,所以返回nil 我刚刚意识到通知程序| |=模拟。。。这可能是问题所在,而且可以肯定的是,如果我将其更改为Notifier=mock,该测试至少可以工作。。。。我从某人的代码中复制了| |=作为一种避免每次重新定义常量的方法(w HTTParty::get);这很管用(?)但这不管用。不过,既然通知程序在第一次被定义为一个mock,并且(我认为)在第二次测试中没有更改,那么为什么第二次测试不起作用呢?