如何在Rails with Minitest中使用嵌套属性设置控制器的单元测试

时间:2017-10-10 02:00:32

标签: ruby-on-rails-4 minitest

我有一个person模型,它是我的Rails 4应用中所有类型用户的基础。我有一个administrator模型,一个worker模型,一个client模型,它们都接受嵌套属性。这是我的administrator模型

class Administrator < ActiveRecord::Base
  belongs_to :person
  accepts_nested_attributes_for :person

  ... other model code here
end

在我的SQLite数据库中,我有一个约束,说person_id不能为空。

administrator的控制器测试失败并显示消息'

ActiveRecord::StatementInvalid: SQLite3::ConstraintException: NOT NULL 
constraint failed: administrators.person_id: INSERT INTO "administrators"
("created_at", "updated_at") VALUES (?, ?)

administrators_controller_test.rb包含以下内容,

setup do
  @administrator = administrators(:administrator_montgomery_burns)
  @person = people(:person_montgomery_burns)
end

test "should create administrator" do
  assert_difference('Administrator.count') do
    post :create,
      administrator: {
        person_id: @administrator.person_id
      }
  end
  assert_redirected_to administrator_path(assigns(:administrator))
end

我也试过了,

test "should create administrator" do
  assert_difference('Administrator.count') do
    post :create,
      administrator: {
        person: {
          first_name: @person.first_name,
          ... all other person attributes
        }
      }
  end

  assert_redirected_to administrator_path(assigns(:administrator))
end

有任何想法应该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

我已经解决了。我查看了开发模式下控制器中的日志文件params哈希值(它工作的地方),以及测试模式下(不是它的地方)。而不是

test "should create administrator" do
  assert_difference('Administrator.count') do
    post :create,
      administrator: {
        person: {
          first_name: @person.first_name,
          ... all other person attributes
        }
      }
  end

  assert_redirected_to administrator_path(assigns(:administrator))
end

使用

test "should create administrator" do
  assert_difference('Administrator.count') do
    post :create,
      administrator: {
        person_attributes: {
          first_name: @person.first_name,
          ... all other person attributes
        }
      }
  end

  assert_redirected_to administrator_path(assigns(:administrator))
end

只需将person:更改为person_attributes: