RSpec的.如何检查对象方法是否被调用?

Mak*_*sov 7 ruby rspec ruby-on-rails

我正在为控制器编写规范:

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
Run Code Online (Sandbox Code Playgroud)

我的控制器看起来像:

def find_similar
 @movies = Movie.find(params[:id]).search_similar
end
Run Code Online (Sandbox Code Playgroud)

运行rspec后,我得到以下内容:

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)>'
Run Code Online (Sandbox Code Playgroud)

我似乎理解并接受,因为在我的控制器代码中我调用了Class(Movie)方法,我没有看到任何方法将"find_similar"与在规范中创建的对象连接起来.

所以问题是 - >检查是否在对象上调用方法的方法是什么?

Pab*_*dez 7

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
Run Code Online (Sandbox Code Playgroud)

值得一提的是,我完全反对这些存根测试,他们只是让代码更改变得更难,实际上只测试代码结构.