RSpec. How to check if an object method is called?

I am writing a specification for a controller:

it 'should call the method that performs the movies search' do movie = Movie.new movie.should_receive(:search_similar) get :find_similar, {:id => '1'} end 

and my controller looks like this:

 def find_similar @movies = Movie.find(params[:id]).search_similar end 

after running rspec, I get the following:

 Failures: 1) MoviesController searching by director name should call the method that performs the movies search Failure/Error: movie.should_receive(:search_similar) (#<Movie:0xaa2a454>).search_similar(any args) expected: 1 time received: 0 times # ./spec/controllers/movies_controller_spec.rb:33:in `block (3 levels) in <top (required)>' 

which I seem to understand and accept, because in my controller code I call the Class (Movie) method and I see no way to associate "find_similar" with the object created in the specification.

So the question is → how to check if a method is called on an object created in spec?

+6
source share
2 answers
 it 'should call the method that performs the movies search' do movie = Movie.new movie.should_receive(:search_similar) Movie.should_receive(:find).and_return(movie) get :find_similar, {:id => '1'} end 

<sub> For what it costs, I am categorically against these tests for all occasions, they just make code changes more complicated and actually test nothing but the structure of the code. Sub>

+7
source

At first, your movie has not yet been saved.

Secondly, not a fact that will have id 1

So try this

 it 'should call the method that performs the movies search' do movie = Movie.create movie.should_receive(:search_similar) get :find_similar, {:id => movie.id} end 
0
source

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


All Articles