1
votes

I want to generate a :stake factory that belongs to a :topic and a :group. The :topic should belong to a :group (as :owner_group) and in this case it should be the same :group (as the one :stake belongs to). Topic also belongs to :membership. In short, I want this to set up valid objects:

it 'should set up all the factories' do
  member = FactoryGirl.create(:membership)
  topic  = FactoryGirl.create(:topic, owner_group: member.group, membership: member)
  stake  = FactoryGirl.create(:stake, group: member.group, topic: topic)
end

But I get the error:

Failure/Error: stake = FactoryGirl.create(:stake, group: member.group, topic: topic) ActiveRecord::RecordInvalid: Validation failed: Group has already been taken

Here are my factories:

factory :user
  sequence(:email) { |n| "foo#{n}@bar.com" }
end

factory :group
  name Faker::Company.name

  factory :owner_group
  end
end

factory :membership
  user
  group
end

factory :topic
  owner_group
  membership
end

factory :stake
  group
  topic
end

topic.rb has this association:

belongs_to :owner_group, class_name: "Group", foreign_key: "group_id"

I've remedied similar errors in the past with rake db:test:prepare, which doesn't work. I've also configured spec_helper.rb with the database_cleaner gem. So I suspect it's how I've set up my factories.

Is there anything in my factory associations or the way I'm creating the objects that's causing this error?

1

1 Answers

1
votes

So it sounds like there is already a Stake with that same Group. I don't see a problem with the factory definition. I would check your test database to make sure the stakes table is empty, but that's probably not the issue. Do you have a before block that is creating a Stake? Or perhaps Topic or Group have an after_create callback that creates an initial Stake automatically?