如何在rspec中干燥多对多的关联作业?

时间:2013-09-02 05:57:34

标签: ruby-on-rails ruby rspec fabrication-gem

每次我想创建Issue时,我都需要将UserLabel相关联。用户has_many标签和标签has_many用户。

问题在于,每次创建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)

我应该把它放在助手班吗?我想提示干一下。

1 个答案:

答案 0 :(得分:1)

这个宝石可以做到这一点: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

之后你可以做这些事情:

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