简体   繁体   English

RSpec控制器销毁测试

[英]RSpec Controller Destroy Testing

I'm building a test application that lets user create/delete posts. 我正在构建一个测试应用程序,允许用户创建/删除帖子。 I'm having a bug in my destroy action that I'm finding difficult to debug. 我的销毁动作中有一个错误,很难调试。 Here's my test: 这是我的测试:

  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

Here's my destroy action: 这是我的销毁动作:

  def destroy
    @post = Post.find_by(id: params[:id])
    if @post
      @post.destroy
    else
      flash[:errors] = "Post doesn't exist"
    end
    render :index
  end

I put a debugger in the action, and it looks like the post is found and deleted properly, so I suspect the issue is with the way I'm evaluating the test. 我在操作中放入了调试器,看起来该帖子已找到并被正确删除,因此我怀疑问题出在我评估测试的方式上。 Here's my failing spec: 这是我失败的规格:

  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

What's going on here? 这里发生了什么?

I think your post is created but after the first count is evaluated. 我认为您的帖子已创建,但在评估了第一笔之后。 Let's assure it's created before with let! 让我们确保它是使用let!创建的let!

let!(:post) { FactoryGirl.create(:post) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM