gpt4 book ai didi

mocking - Rspec、 stub 方法并返回预定义值

转载 作者:行者123 更新时间:2023-12-02 16:51:51 24 4
gpt4 key购买 nike

我想测试这个销毁操作:

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

关于mocking - Rspec、 stub 方法并返回预定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4526119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com