我正在为控制器编写规范:
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)>'
我似乎理解并接受,因为在我的控制器代码中我调用了Class(Movie)方法,我没有看到任何方法将“find_similar”与在规范中创建的对象连接。
所以问题是 - &gt;什么是检查方法是否在对象上调用的方法,在spec?
中创建答案 0 :(得分: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
<子> 值得一提的是,我完全反对这些存根测试,他们只是让代码更改变得更难,实际上只测试代码结构。 子>
答案 1 :(得分:0)
首先,您的电影尚未保留。
第二个,而不是事实,它将具有身份1
所以试试这个
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