【问题标题】:RSpec Mocking Mailer -- fails when called second timeRSpec Mocking Mailer - 第二次调用时失败
【发布时间】:2012-06-14 14:21:42
【问题描述】:

我正在测试一些涉及电子邮件的方法,并尝试使用模拟邮件对象。我显然走错了路,因为测试第一次有效,但随后同样的测试失败了。如果有人能解释这里发生了什么,我将不胜感激。谢谢。

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)>'

【问题讨论】:

  • 我刚刚意识到 Notifier ||= mock... 可能是问题所在,果然,如果我将它更改为 Notifier = mock...,这个测试至少可以工作。我已经复制了||= 来自某人的代码,作为不每次都重新定义常量的一种方式(w HTTParty::get);那行得通(?),但这没有。尽管如此,鉴于 Notifier 第一次被定义为模拟,并且(我认为)第二次测试没有更改,为什么第二次测试不起作用?

标签: ruby-on-rails rspec mocking actionmailer


【解决方案1】:

Rspec 为模拟和期望插入设置/拆卸内容。这确实可以验证should_receive 的期望是否得到满足,并清除对象中设置的模拟,这些对象超出了单一规范。例如,如果您在一个规范中存根 User.find,您不会期望该存根存在于另一个规范中。

所以在第一个规范结束时,rspec 正在删除每个之前的存根设置。因为您正在执行 ||=,所以不会重新创建通知程序,也不会重新创建存根。这反过来意味着当您在第二个规范中调用 should_receive 时,您正在设置一个新的存根。由于这个新存根没有指定的返回值,所以返回 nil。

【讨论】:

    猜你喜欢
    • 2021-04-02
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 2012-07-31
    • 1970-01-01
    相关资源
    最近更新 更多