我的控制器中有这个代码,我想用功能测试来测试这个代码行.

raise ActiveRecord::RecordNotFound if @post.nil?

我应该使用哪种断言方法?

我用以下代码进行了try :

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

推荐答案

你可以做两件事.第一个是让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不会改变行为.

我有时会使用的另一种 Select 是:

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篇文章.

为了简单起见,我通常会 Select 我的第一个解决方案.

Ruby-on-rails相关问答推荐

将会话_store 与:active_record一起使用

对Rails进行枚举不允许空值

SASS,Rails 7:找不到要导入的样式表

如何在不触发每次编译的情况下运行`bin/rails测试`?

Rails 6:强类型原始 SQL 查询返回数组类型

Turbo-Rails:如何将 Turbo Frame 添加到 `application.html.erb`?

计算总价(商品数量*商品价格)

如何在 IRB/Rails 控制台中 suppress 返回值的输出?

Time.zone.now.to_date 是否等同于 Date.today?

如果 URL 不存在,请将 http(s) 添加到 URL?

Rails:包含多态关联

水豚 click_link 与 :href 匹配

在 Ruby on Rails 上,我们如何在控制器中打印调试信息?

如何从邮箱中获取域

何时(如果)合并 ActiveRecord 迁移?

如何在 Rails 3 中订购包含的元素

您可以在弹性 beantalk 环境中运行 rails 控制台或 rake 命令吗?

如何删除删除选项表单 activeAdmin?

是否可以输出rake db:migrate产生的 SQL 更改脚本?

我如何为 Rails3/Bundler 供应 gems