Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 867
Maksim Ravnovesov Avatar asked Apr 07 '12 16:04

Maksim Ravnovesov


People also ask

How do I know if a method was called RSpec?

You can check a method is called or not by using receive in rspec.

Is RSpec TDD or BDD?

RSpec is a Behavior-Driven Development tool for Ruby programmers. BDD is an approach to software development that combines Test-Driven Development, Domain Driven Design and Acceptance Test-Driven Planning. RSpec helps you do the TDD part of that equation, focusing on the documentation and design aspects of TDD.

What is stub in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.

How do I mock a method in RSpec?

Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.


1 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

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.

like image 66
Pablo Fernandez Avatar answered Sep 28 '22 07:09

Pablo Fernandez