0

这是这个问题的后续: Factory_Girl not generate unique records

未创建需求记录的原因是未正确创建用户记录(或至少未正确创建关联)。

给定以下工厂:

factory :user do
  sequence(:name) { |n| "foo#{n}" }
  password "fooBar_1"
  email { "#{name}@example.com" }
  app_setting
  factory :adminUser do |user|
    user.role_assignments { |ra| [ra.association(:adminAssignment)] }
  end
  factory :reader do |user|
    user.role_assignments { |ra| [ra.association(:readerAssignment)] }
  end
end

factory :role_assignment do
  factory :adminAssignment do |ra|
    ra.association :role, factory: :adminRole
  end
  factory :readerAssignment do
    association :role
  end
end

factory :role do
  roleName "reader"
  factory :adminRole do |r|
    r.roleName "Administrator"
  end
end

以下代码片段应生成具有相关角色分配记录的用户,该记录具有角色名称为“管理员”的相关角色记录

user = FactoryGirl.create(:adminUser)

这实际上将在 rails 控制台中工作 - 记录按预期在数据库中创建。但是,在设置期间执行该行代码时,不会保存记录,并且依赖于角色分配的测试会失败。

关于在哪里寻找以找出为什么没有提交记录的任何建议?

4

1 回答 1

1

It turns out that the factory wasn't working quite so well in the Rails console. Although records were being created in all the right tables, the role_assignment record had nil for the user id. Apparently the format I was using to deal with the related many was not correct.

The correct format comes from https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md, and is as follows (for my circumstance):

factory :user do
sequence(:name) { |n| "foo#{n}" }
    password "fooBar_1"
    email { "#{name}@example.com" }
    app_setting
 factory :adminUser do
   after(:create) do |user, evaluator|
     FactoryGirl.create_list(:adminAssignment, 1, user: user)
   end
 end

I still need to clean up the other portions of the user factory, so I haven't included them here. This creates the user, then creates the role and role_assignment which then link properly.

My other problem actually stemmed from the fact that I am doing a major remodel of the application and hadn't looked back at the scope definition in the requirements model before writing the factory, so the records I was creating would never be in scope. Oops.

于 2013-07-13T06:02:47.910 回答