【问题标题】:Rspec - test redirection on unknown db record in production environmentRspec - 在生产环境中测试未知数据库记录的重定向
【发布时间】:2013-01-30 09:03:46
【问题描述】:

我正在开发 Rails 3.2 应用程序,并希望用户在尝试查找不存在的数据库记录时被重定向到错误#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 idvisit physician_path id: "this is not an id"

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

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

【问题讨论】:

    标签: ruby-on-rails rspec tdd


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多