Rspec, stub method and return a prefined value
I want to test this destroy action:
def destroy
@comment = Comment.find(params[:id])
@comment_id = @comment.id
if @comment.delete_permission(current_user.id)
@remove_comment = true
@comment.destroy
else
@remove_comment = false
head :forbidden
end
end
My spec is this:
describe "DELETE 'destroy'" do
describe 'via ajx' do
it "should be successful if permission true" do
comment = Comment.stub(:find).with(37).and_return @comment
comment.should_receive(:delete_permission).with(@user.id).and_return true
comment.should_receive(:destroy)
delete 'destroy', :id => 37
end
end
end
I always get:
comment.should_receive....
expected: 1 time
received: 0 times
Why :delete_permission is never called? Do you have any suggestion on how t开发者_C百科o test it?
You're telling Comment.find
to return @comment
, but you never set the delete_permission
expectation on that object; you set it on the value returned by the stub
call, the comment
local variable.
Try this:
# As Jimmy Cuadra notes, we have no idea what you've assigned to @comment
# But if you're not doing anything super weird, this should work
@comment.should_receive(:delete_permission).with(@user.id).and_return(true)
@comment.should_receive(:destroy)
Comment.stub(:find).with(37).and_return(@comment)
精彩评论