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

ただし、これにより2つのエラーが発生します。

  • 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"

最初のものは、本番環境をモックする際のエラーを暗示しているようです。2 番目のものは、実際のコードを実装したら消えることを願っています。

これら2つのエラーを解決するにはどうすればよいですか? ありがとう!

4

1 に答える 1

1

プレーンな文字列ではなく、Rails.envストアのように見えます: https ://github.com/rails/rails/blob/3096629d297a77a9b64747a0ac2df6b2cbf47a68/railties/lib/rails.rb#L81ActiveSupport::StringEnquirer

production?メソッドをスタブする方が簡単な場合があります。

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