我正在开发 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":String
在visit new_user_session_path
Couldn't find Physician with id=this is not an id
在visit physician_path id: "this is not an id"
第一个似乎暗示了模拟生产环境的错误;一旦我实现了实际代码,第二个有望消失。
我该如何解决这两个错误?谢谢!