如何为具有嵌套属性的控制器设置单元测试,这些控制器在 Rails 中使用 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

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

我已经解决了。我查看了开发模式下控制器(它正在工作的地方)和测试模式(它不在工作的地方)中的日志文件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:即可。

最新更新