简体   繁体   中英

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

I'm writing the spec for 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:

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

after running the 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 invoke the Class (Movie) method and i don't see any way to connect "find_similar" with object, created in the spec.

So the question is -> what is the way to check if the method is called on the object, created in spec?

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

For what is worth, I'm totally against these stub-all-things tests, they just make code changes harder and are actually testing nothing but code structure.

At first, your movie is not persisted yet.

At second, not 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM