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?
You can check a method is called or not by using receive in rspec.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With