Jeffrey Alan Lee
Jeffrey Alan Lee

Reputation: 81

FactoryGirl Does Not Save Records

This is a follow on to this question: Factory_Girl not generating unique records

The reason that requirements records are not being created is because the user records are not being created properly (or at least the associations).

Given the following factories:

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

The following snippet of code, should yield a user with a related role_assignment record with a related role record with a roleName of "Administrator"

user = FactoryGirl.create(:adminUser)

This will actually work in the rails console - records are created in the database as expected. However, when the line of code is executed during setup, the records aren't saved, and tests that rely on the role assignment fail.

Any suggestions on where to look to figure out why the records are not being committed?

Upvotes: 0

Views: 1594

Answers (1)

Jeffrey Alan Lee
Jeffrey Alan Lee

Reputation: 81

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.

Upvotes: 1

Related Questions