FactoryGirl不会与build_attributes输出关联

时间:2015-12-21 20:11:05

标签: ruby ruby-on-rails-4 rspec factory-bot rspec-rails

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

这是我的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"]}>

有什么想法吗?使用attributes_for时,为什么FactoryGirl不输出用户?

1 个答案:

答案 0 :(得分: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