RSpec for should_receive and should_not_receive both passed for Exception

三世轮回 提交于 2020-01-02 01:48:07

问题


I had a really weird rspec case scenario. I tried to test if my function handles exception correctly. And the following is my code:

in User.rb:

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

in 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

The test passed, but when I change ErrorMessage.should_receive(:add) to ErrorMessage.should_not_receive(:add), It also passed, any insights?


回答1:


Since rspec 2.11 exposed one of my tests to exhibit such "abnormality", I decided to raise the issue on github. You may following the discussion at https://github.com/rspec/rspec-mocks/issues/164

Summary: any_instance.should_not_receive is undefined, avoid




回答2:


What you can try to use instead is .should_receive in combination with .never:

ErrorMessage.should_receive(:add).never


来源:https://stackoverflow.com/questions/11319975/rspec-for-should-receive-and-should-not-receive-both-passed-for-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!