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

を、私のコントローラは次のようになります。私は、次の取得はRSpecを実行した後

def find_similar 
@movies = Movie.find(params[:id]).search_similar 
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)>' 

私のコントローラコードではクラス(ムービー)メソッドを呼び出すため、私はオブジェクトに "find_similar"を接続する方法がないので、理解して受け入れますc。

したがって、問題は - >メソッドがオブジェクトに対して呼び出されたかどうかを確認する方法は何ですか?

答えて

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 

を試してみてください、私はこれらのスタブすべてのものに対して全くですコードを変更するだけで、コード構造をテストするだけです。 "ID" の

+0

over-stubbingについて同意すると、アプリが動作しているかどうかを確認するよりも、そのメソッドのスタブを確認するテストが多すぎます。 – njorden

+0

いいです。ここにはおいしさに関するドキュメントがあります:https://www.relishapp.com/rspec/rspec-mocks/v/2-5/docs/message-expectationsこのビットが必要でした。obj.should_receive(:message).with( 'more_than '、' one_argument ') ' – TomDunning

+0

" "タグの面白い使い方 – fotanus

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

おかげで、あなたは絶対的に正しいです。主な問題は、メッセージが同じで、コードを変更した後、まだここがある - >失敗/エラー:。 (#<映画:0xae08b48>):movie.should_receive(search_similar)search_similar(任意の引数) が予想さ:1時間 を受信:= ID: '、iは固定具と、いくつかのオブジェクトをロード行う –

+0

には仕様の最初のバージョン' Movie.find([ID]のparams)にすることを不思議です> '1' ... – MikDiet

+0

.. '有するのいずれかをRecordNotFound'を上げていない:0回 –

関連する問題