How can I dry many to many association assignments in rspec?

602 views Asked by At

Every time I want to create an Issue, I need to link User with Label. User has_many Labels and Labels has_many Users.

The problem is that I need to repeat this in a lot of specs every time I create an Issue.

let(:label) { Fabricate(:label) }
let(:responsible) { Fabricate(:responsible) }

before do
  label.stub(:users).and_return([responsible])
  responsible.stub(:labels).and_return([label])
end

let(:issue) { Fabricate(:issue, label: label, responsible: responsible)

Should I place this in a helper class? I would like tips to dry it up.

1

There are 1 answers

0
hedgesky On

This gem could do the thing: https://github.com/thoughtbot/factory_girl

factory :label do
  name    "label example"
  user
end

factory :user do
  name    "John Doe"
  after(:create) do |user|
    FactoryGirl.create_list(:label, 1, user: user)
  end
end

factory :issue do
  name 'issue'
  after(:create) do |issue|
    issue.users = FactoryGirl.create_list(:user, 1)
  end
end

And after that you could do such things:

issue = FactoryGirl.create(:issue)
issue.users # returns array with 1 user
issue.users.first.label # returns array with one label