我正在构建一个允许用户创建/删除帖子的测试应用程序。我的销毁行动中有一个错误,我发现很难调试。这是我的考试:
describe '#destroy' do
context 'existing post' do
let (:post) { FactoryGirl.create(:post) }
it 'removes post from table' do
expect { delete :destroy, id: post }.to change { Post.count }.by(-1)
end
it 'renders index template' do
delete :destroy, id: post
expect(response).to render_template('index')
end
end
context 'delete a non-existent post' do
it 'creates an error message' do
delete :destroy, id: 10000
expect(flash[:errors]).to include("Post doesn't exist")
end
end
end
这是我的毁灭行动:
def destroy
@post = Post.find_by(id: params[:id])
if @post
@post.destroy
else
flash[:errors] = "Post doesn't exist"
end
render :index
end
我在操作中放了一个调试器,看起来帖子被找到并正确删除了,所以我怀疑问题与我评估测试的方式有关。这是我失败的规范:
1) PostsController#destroy existing post removes post from table
Failure/Error: expect { delete :destroy, id: post }.to change { Post.count }.by(-1)
expected result to have changed by -1, but was changed by 0
这里发生了什么?
答案 0 :(得分:3)
我认为您的帖子已创建,但在评估第一个计数后。让我们确保之前使用let!
let!(:post) { FactoryGirl.create(:post) }