How to check if a method is called in RSpec but does not override the return value

There are already questions , but they all override the return values ​​to nilif not called.and_return

PROBLEM

I am wondering if there is a way to simply check if a method is called with expect_any_instance_of(Object).to receive(:somemethod), and it works fine, without overriding or affecting the return value .somemethod.

  • RSpec-3.4.0
  • rails 4.2

Consider the following:

# rspec
it 'gets associated user' do
  expect_any_instance_of(Post).to receive(:get_associated_user)
  Manager.run_processes
end

# manager.rb
class Manager
  def self.run_processes
    associated_user = Category.first.posts.first.get_associated_user
    associated_user.destroy!
  end
end

The spectrum above, although it will work because it :get_associated_useris called in run_processes, however, it raises NoMethodError: undefined method 'destroy!' for NilClassprecisely because I made fun of :get_associated_userany Post instance.

.and_return, expect_any_instance_of(Post).to receive(:get_associated_user).and_return(User.first), , ( ), , .

.and_return(correct_user), correct_user - , , . , , Category.first.posts.first.get_associated_user , . , , .

+4
1

and_call_original , " " .

https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations/calling-the-original-method

expect_any_instance_of(Post).to receive(:get_associated_user).and_call_original

expect_any_instance_of , , , .

# test what it does - not how it does it.
it 'destroys the associated user' do
  expect { Manager.run_processes }.to change(Category.first.posts.first.users, :count).by(-1)
end
+9

Source: https://habr.com/ru/post/1629168/


All Articles