【问题标题】:Rspec testing ActiveAdmin create actionRspec 测试 ActiveAdmin 创建操作
【发布时间】:2015-10-19 21:08:03
【问题描述】:

我的 rails 应用程序有模型 Institution,只有 AdminUser 可以创建。我的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 中测试此路由/操作?关于测试 ActiveAdmin 的在线资源很少。我能找到的只有thisthisthis,最后一个似乎最接近我正在寻找的东西,但不完全是。

我只是想要一种方法来测试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

没有创建机构,但我没有收到任何错误。任何帮助表示赞赏,谢谢。

-格雷格

【问题讨论】:

  • expect{post :create, name: "test_name", email: "test@email.com"}.to change{Institution.count}.by(1)

标签: ruby-on-rails ruby rspec activeadmin


【解决方案1】:

尝试使用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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多