每次我想创建Issue
时,我都需要将User
与Label
相关联。用户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)
我应该把它放在助手班吗?我想提示干一下。
答案 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