测试引发的错误

时间:2014-08-15 14:27:42

标签: ruby-on-rails rspec

所以我有这段代码:

begin
    @location = Location.find(params[:id])
rescue ActiveRecord::RecordNotFound
    puts 'ERROR MUST HAVE BEEN RAISED IF I APPEAR'
    render action: :new, status: 404
end

并在此进行了测试:

let(:invalid_request){ get :show, id: Location.count + 1 }
describe 'runtime' do
    before { invalid_request }

    it 'should raise error ActiveRecord::RecordNotFound' do
        expect { invalid_request }.to raise_error ActiveRecord::RecordNotFound
    end
end

然而当我实现这个期望时,我得到了这个自相矛盾的输出:

      runtime
ERROR MUST HAVE BEEN RAISED IF I APPEAR
        should raise error ActiveRecord::RecordNotFound (FAILED - 1)

Failures:

  1) LocationsController#show when location doesn't exist runtime should raise error ActiveRecord::RecordNotFound
     Failure/Error: expect { invalid_request }.to raise_error ActiveRecord::RecordNotFound
       expected ActiveRecord::RecordNotFound but nothing was raised
     # ./spec/controllers/locations_controller_spec.rb:45:in `block (5 levels) in <top (required)>'

那么为什么会这样呢? Rails会自动引发错误,所以即使我没有手动提出它,它仍然会被提升并且应该是可测试的...... < / p>

1 个答案:

答案 0 :(得分:0)

您的代码不会引发错误:

  • 它被提出
  • 但是获救了

最后,没有错误。

你应该测试你得到404。

顺便说一下,render new有404感觉不对,你宁愿重定向。