Rspec 测试 ActiveAdmin 创建操作

Rspec testing ActiveAdmin create action

我的 rails 应用程序具有只有 AdminUser 可以创建的模型 Institution。我的 app/admin/institution.rb 文件如下所示:

ActiveAdmin.register Institution do

  permit_params :name, :email

  index do
    id_column
    %W(name email).each do |field|
      column field.to_sym
    end
    actions
  end

  form do |f|
    f.inputs do
      f.input :name
      f.input :email
      f.actions
    end

  end

end

对应的创建机构路径为POST /admin/institutions

有没有一种简单的方法可以在 rspec 中测试这个 route/action?关于测试 ActiveAdmin 的在线资源很少。我能找到的只有 this, this and this,最后一个似乎最接近我要找的东西,但不完全是。

我只是想要一种方法来测试 POST /admin/institutions 端点,只向它传递两个必需的参数(姓名和电子邮件)。但是以下 rspec 测试失败:

describe Admin::InstitutionsController, :type => :controller do

  before(:each) do
    @user = FactoryGirl.create(:admin_user)
    sign_in @user
  end

  it 'creates an institution' do
    post :create, name: "test_name", email: "test@email.com"
    expect(Institution.all.count).to eq(1)
  end

end

没有创建任何机构,但我没有收到任何错误。感谢您的帮助,谢谢。

-格雷格

尝试使用 institution 键为参数命名空间。在大多数资源 Rails 中基于表单的表单字段按模型名称分组。试试以下方法:

it 'creates an institution' do
  post :create, institution: { name: "test_name", email: "test@email.com" }
  expect(Institution.all.count).to eq(1)
end

原因是表单如何将这两个字段呈现为文本输入(检查 HTML 来源)。该字段的名称应为:

  • institution[name]
  • institution[email]