2010-03-22 114 views
31

我在我的控制器中有这段代码,并且想用功能测试来测试这个代码行。如何在我的Rails应用程序中测试ActiveRecord :: RecordNotFound?

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.' 

回答

49

有两件事情可以做。首先是让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 

你应该阅读更多关于#rescue_from上的ActiveSupport API。

为了简单起见,我通常会使用我的第一个解决方案。

+0

谢谢你,我喜欢那样! – xaver23 2010-03-22 14:19:26

+0

我喜欢在我的ApplicationController(application_controller.rb)中使用'rescue_from ActiveRecord :: RecordNotFound',因为我不喜欢'assert_raises'块。 – 2011-01-02 22:40:48

相关问题