Rspec,stub方法并返回一个预定义的值

时间:2010-12-24 11:45:53

标签: mocking rspec

我想测试这个破坏行为:

  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

我的规格是:

    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

我总是得到:

comment.should_receive....
expected: 1 time
received: 0 times

为什么:从不调用delete_permission?你对如何测试它有什么建议吗?

1 个答案:

答案 0 :(得分:6)

您告诉Comment.find返回@comment,但您从未对该对象设置delete_permission期望;您可以将其设置为stub调用返回的值comment局部变量。

试试这个:

# 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)