【问题标题】:Rails tests with activeadmin使用 activeadmin 进行 Rails 测试
【发布时间】:2015-04-02 14:56:54
【问题描述】:

我在我的 Rails 项目中使用 activeadmin,我想知道如何对其进行测试。我在互联网上查看,但没有关于它的文档。 我有一个设置资源,但我禁用了创建新资源或删除它的可能性。

我想知道如何测试这些路由不存在或以其他方式确保它无法访问。 在我的实际中,虽然我试图将此页面断言为 404,但测试似乎抛出了这个错误(这是我试图测试的!!!):ActionController::UrlGenerationError: No route matches {:action=>"new", :controller=>"admin/settings"}

我不使用 Rspec,而是使用 Rails 的 Minitest
感谢您的帮助!

我的 activeadmin 文件

ActiveAdmin.register Setting do
    actions :all, except: [:new, :destroy]
    …
end

我的测试

require 'test_helper'

class Admin::SettingsControllerTest < ActionController::TestCase
   include Devise::TestHelpers
   setup :initialize_settings

   test 'should throw 404 if trying to access new action' do
     get :new
     assert_response 404
   end

   def initialize_settings
     sign_in users(:one)
   end
end

我的项目

  • Rails 4.2
  • Ruby 2.2.0
  • Minitest(非 RSPEC)

【问题讨论】:

  • 如果你从这一行删除 :new 操作 :all,除了: [:new, :destroy] 你还会得到同样的错误吗?您是否尝试过而不是 assert_response ... 做类似这样的事情 value(response).must_respond_with 404

标签: ruby-on-rails testing activeadmin minitest


【解决方案1】:

您需要的是集成测试,特别是那些将测试路由的测试,或者在您的情况下,测试路由的缺失。不存在的操作将引发ActionController::RoutingError

# test/routes/admin/settings_test.rb
require 'test_helper'

class Admin::SettingsRouteTest < ActionDispatch::IntegrationTest  
  test 'create' do
    assert_raises(ActionController::RoutingError) do
      post '/admin/settings'
    end
  end

  test 'destroy' do
    assert_raises(ActionController::RoutingError) do
      delete '/admin/settings/1'
    end
  end

  test 'edit' do
    assert_routing '/admin/settings/1/edit', controller: 'admin/settings', action: 'edit', id: '1'
  end

  test 'index' do
    assert_routing '/admin/settings', controller: 'admin/settings', action: 'index'
  end

  test 'new' do
    assert_routing '/admin/settings/new', controller: 'admin/settings', action: 'show', id: 'new'
  end

  test 'update' do
    assert_routing({ method: 'patch', path: '/admin/settings/1' }, { controller: 'admin/settings', action: 'update', id: '1' })
  end
end

请注意,new 操作会退回到 ID 为“新”的 show 操作。

观察:如果您要删除 :new 操作,您可能还打算删除 :create 操作,这样就无法通过该路径创建任何记录。

# app/admin/setting.rb
ActiveAdmin.register Setting do
  actions :all, except: [:new, :create, :destroy]
end

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多