Rspec / Rails控制器测试404不工作

时间:2014-07-16 16:42:53

标签: ruby-on-rails rspec

这是我的测试:

  describe "GET show" do

    it "assigns service_request as @service_request" do
      get :show, { company_id: @company.id, id: service_request.id }
      expect(assigns(:service_request)).to eq service_request
    end

    it "returns 404 when service_request is not found" do
      get :show, { company_id: @company.id, id: "foo" }
      expect(response.status).to eq 404
    end

  end

终端中的错误是:

  1) ServiceRequestsController GET show returns 404 when service_request is not found
     Failure/Error: get :show, { company_id: @company.id, id: "foo" }
     ActiveRecord::RecordNotFound:
       Couldn't find ServiceRequest with 'id'=foo [WHERE (company_id IS NOT NULL)]
     # ./spec/controllers/service_requests_controller_spec.rb:44:in `block (3 levels) in <top (required)>'
     # -e:1:in `<main>'

显然这不正确,但我不确定是什么错误

3 个答案:

答案 0 :(得分:3)

Rails抛出ActiveRecord :: RecordNotFound错误,而不是重定向到一般的404页面。您需要使用控制器中的rescue_from处理该错误,并重定向到状态为404的404视图。

答案 1 :(得分:1)

遇到了这个问题。事实证明,在测试环境中,rails显示错误消息以帮助调试。

This blog post详细介绍了一种获取“类似于生产”的错误响应以测试您的API响应的方法。建议创建一个帮助器spec/support/error_responses.rb

module ErrorResponses

  def respond_without_detailed_exceptions
    env_config = Rails.application.env_config
    original_show_exceptions = env_config["action_dispatch.show_exceptions"]
    original_show_detailed_exceptions = env_config["action_dispatch.show_detailed_exceptions"]
    env_config["action_dispatch.show_exceptions"] = true
    env_config["action_dispatch.show_detailed_exceptions"] = false
    yield
  ensure
    env_config["action_dispatch.show_exceptions"] = original_show_exceptions
    env_config["action_dispatch.show_detailed_exceptions"] = original_show_detailed_exceptions
  end

end

RSpec.configure do |config|
  config.include ErrorResponses

  config.around(realistic_error_responses: true) do |example|
    respond_without_detailed_exceptions(&example)
  end
end

然后可以在您的情况下按以下方式使用它。请注意使用:realistic_error_responses

describe "GET show", :realistic_error_responses do
  it "assigns service_request as @service_request" do
    get :show, { company_id: @company.id, id: service_request.id }
    expect(assigns(:service_request)).to eq service_request
  end

  it "returns 404 when service_request is not found" do
    get :show, { company_id: @company.id, id: "foo" }
    expect(response.status).to eq 404
  end
end

答案 2 :(得分:0)

这样写的更好的方法。

it "returns 404 when service_request is not found" do
  get :show, { company_id: @company.id, id: "foo" }
  expect(response).to have_http_status(:not_found)
end

您还可以找到其他Rails HTTP状态符号here