【问题标题】:Rspec, stub method and return a prefined valueRspec,存根方法并返回一个预定义的值
【发布时间】:2010-12-24 11:45:53
【问题描述】:

我想测试这个销毁动作:

  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 永远不会被调用?您对如何测试它有什么建议吗?

【问题讨论】:

  • 我以为comment = Comment.stub(:find).with(37).and_return @comment 会将@comment 分配给评论。谢谢

标签: mocking rspec


【解决方案1】:

您告诉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)

【讨论】:

    猜你喜欢
    • 2021-03-15
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2011-08-22
    • 2015-11-12
    相关资源
    最近更新 更多