2012-04-07 51 views
6

我正在写控制器规格:RSpec。如何检查对象方法是否被调用?

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 

和我的控制器看起来像:

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

我看来:运行RSpec的我得到以下后

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

理解和接受,因为在我的控制器代码中,我调用了Class(Movie)方法,并且我没有看到任何方式将“find_similar”与对象创建的连接C。

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

回答

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 

对于什么是值得的,我完全反对这些存根,所有的东西测试,他们只是使代码更改更难,实际上只是测试代码结构。

+0

同意过度存根,看到太多的测试检查方法存根工作,而不是检查应用程序的工作原理。 – njorden 2012-06-18 20:08:34

+0

不错的一个。这里是关于津津乐道的文档:https://www.relishapp.com/rspec/rspec-mocks/v/2-5/docs/message-expectations我需要这一点'obj.should_receive(:message).with('more_than ','one_argument')' – TomDunning 2013-10-11 10:29:02

+0

有趣的使用“”的标签 – fotanus 2013-10-31 13:11:57

0

起初,你的电影还没有持久。

在第二,而不是事实,这将有ID 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 
+0

感谢您的“ID”,您绝对正确。但主要的问题仍然在这里,改变代码后的消息是相同的 - >失败/错误:movie.should_receive(:search_similar) (#)。search_similar(any args) expected:1 time received:0 times – 2012-04-07 16:29:12

+0

奇怪的是,在第一版spec' Movie.find(params [:id])'不会引发'RecordNotFound' .. – MikDiet 2012-04-07 16:35:35

+0

我确实加载了一些具有fixture的对象,其中一个有:id = >'1'... – 2012-04-07 17:22:19

相关问题