如果在区块主题中设置了请求操作,如何正确测试匿名控制器

时间:2018-12-27 02:33:43

标签: ruby-on-rails rspec

我测试资源控制器。为此,我在测试匿名控制器中创建了

我有以下rspec测试:

describe '#destroy' do
    before { allow(controller).to receive(:custom_actions_path).and_return('/') }
    subject { delete :destroy, params: { id: post.id, locale: user.language }}

    it 'delete resource' do
      expect { Post }.to change(Post, :count).by(-1)
    end 

    it 'instant variables are exist' do
      assigns(:resource).should_not be_nil
    end

    it { expect(response).to redirect_to('/') }

    it { expect(response.code).to eq '302' }
  end
end

测试总是失败:

1) ResourceController::Crudify#destroy delete resource
     Failure/Error: expect { Post }.to change(Post, :count).by(-1)
       expected `Post.count` to have changed by -1, but was changed by 0
     # ./spec/unit/controllers/concerns/resource_controller/crudify_spec.rb:162:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:47:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:46:in `block (2 levels) in <top (required)>'

  2) ResourceController::Crudify#destroy instant variables are exist
     Failure/Error: assigns(:resource).should_not be_nil

       expected: not nil
            got: nil

如果行动要求破坏了我通过的区块主题,那么正确的测试方法将如何破坏?谢谢

1 个答案:

答案 0 :(得分:0)

在某些情况下,您应该显式调用subject。请注意第一个示例:应该将其传递给块,以便RSpec实际上可以评估状态之前和之后。

describe '#destroy' do
    before { allow(controller).to receive(:custom_actions_path).and_return('/') }
    subject { delete :destroy, params: { id: post.id, locale: user.language }}

    it 'deletes resource' do
      expect { subject }.to change(Post, :count).by(1)
    end 
end