Rspec stub method and return a preset value

I want to check this destruction 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 specification is as follows:

    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 suggestions for testing it?

+3
source share
1 answer

You pass in Comment.findfor a refund @comment, but you never set a wait delete_permissionon this object; you set it to the value returned by the call stub, a local variable comment.

Try the following:

# 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)
+6
source

Source: https://habr.com/ru/post/1781987/


All Articles