作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想测试这个销毁操作:
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/
我是一名优秀的程序员,十分优秀!