由于设置factory_girl的困难,我正在进行一些测试失败。我有一个JOB类和一个TEMPLATE类。还有一个PROVIDER用户类。作业属于JOB和TEMPLATE。但是,我当前的工厂分别指定了提供者和模板。
这一次突破:
expect { post :create, job: attributes_for(:job, provider_id: provider.id) }.to change(Job,:count).by(1)
这一项工作(手动定义):
expect { post :create, job: attributes_for(:job, provider_id: provider.id, template_id: create(:template, provider_id: provider.id) ) }.to change(Job,:count).by(1)
有没有办法设置工厂将模板自动创建为属于提供者?
factory :job do
provider
template
end
factory :template do
template_type { Faker::Lorem.word }
template_text { Faker::Lorem.paragraph(3) }
end
答案 0 :(得分:1)
根据我的描述,模板还应该引用创建的提供程序。你可以写这样的东西,比如
factory :job do
provider
after(:build) do |job|
job.template = build(:template, provider: job.provider)
end
end
您可以在https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#callbacks
中了解相关信息答案 1 :(得分:0)
要处理不返回关联的attributes_,您可以定义自己的attributes_for,包括这些。我曾经写过一个定制的,非常复杂的方法,包括所有“可访问”的关联。我会在这里包含它,以防你想使用它
# In contrast with "attributes_for", "attributes_for_incl_associations" does return attributes
# for accessible associations as well
# Inspired by: http://stackoverflow.com/questions/10290286/factorygirl-why-does-attributes-for-omit-some-attributes
def attributes_for_incl_associations(*args)
obj = FactoryGirl.build(*args); klass = obj.class
# Find all accessible attributes in object's class
if defined? controller and controller.current_user and klass.active_authorizers.include? controller.current_user.role
accessible = klass.accessible_attributes(controller.current_user.role)
else
accessible = klass.accessible_attributes(:default)
end
# Find all associations in object's class
associations = klass.reflect_on_all_associations(:belongs_to).map { |a| "#{a.name}_id" }
# Find all accessible associations in the created object's attributes
accessible_associations = obj.attributes.delete_if do |k, v|
!accessible.include?(k) || !associations.member?(k)
end
# Remove all attributes from FactoryGirl attributes that are not accessible
factory_attributes = FactoryGirl.attributes_for(*args).delete_if do |k, v|
!accessible.include?(k)
end
# Merge FactoryGirl attributes with accessible associations
factory_attributes.merge(accessible_associations.symbolize_keys)
end