2011-04-20 10 views
1

特定のコントローラアクションに対してインスタンスメソッドが1回呼び出されることをアサートしようとしています。何らかの理由でテストが機能しません。コードは実際にそれが想定していることを行います。コントローラでインスタンスメソッドが1回呼び出されることをアサートします。

私は(あなたには、いくつかのコードを持って推測しているRSpecの1.xとfactory_girl

テスト

context 'as a regular API user' do 
    before do 
    login_as_regular_user 
    Feed.superfeedr_api.stub!(:pingable?).and_return(true) 
    @feed_entry = Factory(:feed_entry) 
    post :read, :id => @feed_entry.id, :format => 'json' 
    end 

    it "should call read_by method once" do 
    @user = Factory.create(:user) 
    controller.stub!(:current_account).and_return(@user.account) 

    @feed_entry.should_receive(:read_by).once 
    post :read, :id => @feed_entry.id, :format => 'json'   
    end 

    it { should respond_with(204)} 
    it { should assign_to(:feed_entry).with(@feed_entry) } 
    it { should respond_with_content_type(/json/) }    
end 

コントローラ

# POST /entries/1234/read - mark as read 
# DELETE /entries/1234/read - mark as unread 
def read 
    if request.post?  
    @feed_entry.read_by(current_account) 
    elsif request.delete? 
    @feed_entry.unread_by(current_account) 
    end  

    respond_to do |format| 
    format.html { redirect_to topic_path(params[:topic_id]) } 
    format.json { render :nothing => :true, :status => :no_content } 
    format.plist { render :nothing => :true, :status => :no_content } 
    end 
end 

エラー

1) 
Spec::Mocks::MockExpectationError in 'FeedEntriesController.read as a regular API user should call read_by method once' 
#<FeedEntry:0x107db8758> expected :read_by with (any args) once, but received it 0 times 
./spec/controllers/feed_entries_controller_spec.rb:82: 

Finished in 2.242711 seconds 

25 examples, 1 failure, 3 pending 

答えて

2

を使用していますそれは翔じゃないidでFeedEntryを見つけ、@feed_entryに割り当てる例ではWN):

# controller 
@feed_entry = FeedEntry.find(params[:id]) 

findメソッドは、あなたの工場のインスタンスを返すようにスタブする必要があります

# spec 
FeedEntry.should_receive(:find).and_return(@feed_entry) 

それができますテスト中のコード内のインスタンス変数名と仕様内のインスタンス変数名が同じ名前のときに混乱します。それらが異なるオブジェクトであることを忘れないでください。

+0

鮮やかな、どういうわけか私はこの明白な問題を見ませんでした。ありがとうございました。 – brupm

関連する問題