我正在开发一个Rails 3.2应用程序,并希望用户在尝试查找不存在的db记录时重定向到错误#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"
第一个似乎暗示了嘲弄生产环境的错误;一旦我实现了实际的代码,第二个就会消失。
如何解决这两个错误?谢谢!
答案 0 :(得分: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)