1

我正在开发 Rails 3.2 应用程序,并希望用户在尝试查找不存在的数据库记录时被重定向到 errors#index 处的自定义错误页面。

这是我在应用程序控制器中执行此操作的代码:

if Rails.env.production?
  rescue_from Exception, with: :display_error
  rescue_from ActiveRecord::RecordNotFound, with: :display_error
end

private
def display_error
  render "errors/index", status: 404
end

这实际上在生产模式下工作正常。现在的问题是,我如何事先测试它?我试过这个:

it "leads to error page on unknown db record" do
  Rails.stub(:env).and_return("production")

  # Sign in
  @valid_user = FactoryGirl.create(:valid_user)
  visit new_user_session_path
  fill_in "Email", with: @valid_user.email
  fill_in "Password", with: @valid_user.password
  click_button "Sign in"

  # Trigger exception
  visit physician_path id: "this is not an id"
  assert_contain "You blew it!"
end

但是,这给我留下了两个错误:

  • undefined method 'development?' for "production":Stringvisit new_user_session_path
  • Couldn't find Physician with id=this is not an idvisit physician_path id: "this is not an id"

第一个似乎暗示了模拟生产环境的错误;一旦我实现了实际代码,第二个有望消失。

我该如何解决这两个错误?谢谢!

4

1 回答 1

1

它看起来像Rails.env存储ActiveSupport::StringEnquirer而不是普通字符串:https ://github.com/rails/rails/blob/3096629d297a77a9b64747a0ac2df6b2cbf47a68/railties/lib/rails.rb#L81

将方法存根可能更容易production?

Rails.env.stub(:production?).and_return(true)
于 2013-01-30T13:41:49.020 回答