【问题标题】:RSpec for should_receive and should_not_receive both passed for Exceptionshould_receive 和 should_not_receive 的 RSpec 都通过了异常
【发布时间】:2012-07-03 22:16:31
【问题描述】:

我有一个非常奇怪的 rspec 案例场景。我试图测试我的函数是否正确处理异常。以下是我的代码:

在 User.rb 中:

def welcome_user
      begin
        send_welcome_mail(self)
      rescue Exception => exception
         ErrorMessage.add(exception, user_id: self.id)
      end
    end
end

在 user_spec.rb 中

it "adds to error message if an exception is thrown" do
  mock_user = User.new
  mock_user.stub(:send_welcome_mail).and_raise(Exception)
  ErrorMessage.should_receive(:add)
  mock_user.welcome_user
end

测试通过了,但是当我将ErrorMessage.should_receive(:add)更改为ErrorMessage.should_not_receive(:add)时,它也通过了,有什么见解吗?

【问题讨论】:

  • 我遇到了一个发生同样事情的测试,但它在 rspec 2.11 中消失了。看看这对你有没有影响

标签: ruby-on-rails rspec


【解决方案1】:

由于 rspec 2.11 暴露了我的一项测试以表现出这种“异常”,我决定在 github 上提出这个问题。您可以关注https://github.com/rspec/rspec-mocks/issues/164的讨论

总结:any_instance.should_not_receive 未定义,避免

【讨论】:

  • 我最终设法解决了这个问题,原来我用异常排除的方法在之前的逻辑流程中也被调用过,这是问题的主要问题。
【解决方案2】:

您可以尝试使用.should_receive.never 结合使用:

ErrorMessage.should_receive(:add).never

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 2014-02-11
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    相关资源
    最近更新 更多