7

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

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

我的控制器看起来像:

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

运行 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)>'

我似乎理解并接受,因为在我的控制器代码中,我调用了类(电影)方法,但我看不到任何将“find_similar”与规范中创建的对象连接起来的方法。

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

4

2 回答 2

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

值得一提的是,我完全反对这些 stub-all-things 测试,它们只会使代码更改更加困难,实际上只测试代码结构。

于 2012-04-07T17:00:12.527 回答
0

起初,您的电影尚未持久化。

其次,不是事实,那将有 id1

所以试试这个

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
于 2012-04-07T16:20:48.100 回答