我有一个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
有任何想法应该如何做到这一点?
答案 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:
。