2012-04-07 116 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

相關問題