2011-04-20 55 views
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

我猜你有一些代碼(這不是笑在本例中WN),通過ID找到FeedEntry並賦予它@feed_entry:

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

需要存根,以便查找方法返回你的工廠實例:

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

它可以是當被測試代碼和規範中的實例變量名稱具有相同的名稱時會混淆 - 不要忘記它們是不同的對象。

+0

輝煌,不知何故,我沒有看到這個明顯的問題。謝謝。 – brupm 2011-04-21 15:56:38

相關問題