2015-12-21 58 views
0

我可能在这里做了一些非常愚蠢的事情,但我无法通过测试,因为FactoryGirl.attributes_for未输出关系字段。FactoryGirl不会输出与build_attributes的关联

这里是我的project厂:

FactoryGirl.define do 
    factory :project do 
    status 'active' 
    loan_amount 5000 
    start_date Time.now 
    end_date Time.now + 2.week.to_i 
    description "Sample Project" 
    user 
    end 
end 

这里是我试图让这个测试通过测试:

let(:user) { FactoryGirl.create(:user) } 
let(:project_attributes) { FactoryGirl.attributes_for(:project, user: user) } 

it 'assigns a newly created project as @project' do 
    post :create, { project: project_attributes } 
    expect(assigns(:project)).to be_a(Project) 
    expect(assigns(:project)).to be_persisted 
end 

这是project_attributes输出:

{:status=>"active", :loan_amount=>5000, :start_date=>2015-12-21 12:07:32 -0800, :end_date=>2016-01-04 12:07:32 -0800, :description=>"Sample Project"} 

这给了我一个错误:

@messages={:user=>["can't be blank"]}> 

任何想法?为什么FactoryGirl在使用attributes_for时不输出用户?

+0

这可能是'attributes_for'无法识别的关联。当你做'user_id:user.id'时会发生什么? – steel

回答

0

它看起来像你的:project工厂定义是有点关闭。如果项目belongs_to用户,工厂需要说association :user,如

factory :project do 
    status 'active' 
    loan_amount 5000 
    start_date Time.now 
    end_date Time.now + 2.week.to_i 
    description "Sample Project" 
    association :user 
end 
+0

这仍然不会输出用户作为'FactoryGirl.attributes_for(:project,user:user)的一部分''user'对于'association:user,factory:user'是可接受的简写形式 – doremi

+0

尝试'FactoryGirl.build(:project,user :user).attributes' – eugen

+0

问题在于'status'是一个枚举,现在'.attributes'将状态设置为'1'导致错误:''1'不是一个有效的状态' – doremi