【问题标题】:How can I test ActiveRecord::RecordNotFound in my rails app?如何在我的 rails 应用程序中测试 ActiveRecord::RecordNotFound?
【发布时间】:2010-03-22 12:51:00
【问题描述】:

我的控制器中有这段代码,想通过功能测试来测试这段代码。

raise ActiveRecord::RecordNotFound if @post.nil?

我应该使用哪种断言方法? 我使用内置的 rails 2.3.5 测试框架。

我用这段代码试了一下:

  test "should return 404 if page doesn't exist." do
    get :show, :url => ["nothing", "here"]
    assert_response :missing
  end

但这对我不起作用。得到这个测试输出:

test_should_return_404_if_page_doesn't_exist.(PageControllerTest):
ActiveRecord::RecordNotFound: ActiveRecord::RecordNotFound
app/controllers/page_controller.rb:7:in `show'
/test/functional/page_controller_test.rb:21:in `test_should_return_404_if_page_doesn't_exist.'

【问题讨论】:

    标签: ruby-on-rails ruby testing activerecord


    【解决方案1】:

    您可以做两件事。首先是让 ActionController 在救援 ActiveRecord::RecordNotFound 时提供默认动作:

    class PostsControllerTest < ActionController::TestCase
      test "raises RecordNotFound when not found" do
        assert_raises(ActiveRecord::RecordNotFound) do
          get :show, :id => 1234
        end
      end
    end
    

    使用此方法,您无法断言渲染的内容。你必须相信 Rails/ActionController 不会改变行为。

    我有时使用的另一种方法是:

    class PostsControllerTest < ActionController::TestCase
      test "renders post_missing page, and returns 404" do
        get :show, params: { :id => 1234 }
    
        assert_response :not_found
        assert_template "post_missing"
      end
    end
    
    class PostsController < ApplicationController
      def show
        @post = current_user.posts.find_by!(slug: params[:slug])
      end
    
      rescue_from ActiveRecord::RecordNotFound do
        render :action => "post_missing", :status => :not_found
      end
    end
    

    您应该在 ActiveSupport API 上阅读更多关于 #rescue_from 的信息。

    为简单起见,我通常采用第一种解决方案。

    【讨论】:

    • 我喜欢 rescue_from ActiveRecord::RecordNotFound 在我的 ApplicationController(在 application_controller.rb 中),因为我不喜欢 assert_raises 块。
    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多