Rails:添加accepts_nested_attributes_for后无法与Factory Girl构建对象

时间:2016-02-10 07:26:02

标签: ruby-on-rails factory-bot

启用accepts_nested_attributes_for时,我无法让Factory Girl生成User对象。

鉴于模型:

class Account < ApplicationRecord
  belongs_to :meta, polymorphic: true, dependent: :destroy
end

class User < ApplicationRecord
  has_one :account, as: :meta
  validates :fname, presence: true
  validates :lname, presence: true
  validates_presence_of :account
  #accepts_nested_attributes_for :account
end

而且,工厂:

FactoryGirl.define do   
  factory :account do
    sequence(:email) { |n| "account#{n}@mack.com" }
    password "abcdef123"
    password_confirmation "abcdef123"
    confirmed_at Date.today   
  end 
end

FactoryGirl.define do   
  factory :user do
    sequence(:fname) { |n| "first#{n}" }
    sequence(:lname) { |n| "last#{n}" }
    after(:build) do |user|
      user.build_account attributes_for(:account)
    end   
  end 
end

以下规范:

describe User, :type => :model do

  it "has a valid factory" do
    user = build(:user)
    expect(user).to be_valid
  end
end
如果我取消注释User模型中的accepts_nested_attributes_for,则

失败。我想使用嵌套属性来处理User对象,但我无法弄清楚如何让FactorGirl构建一个启用了嵌套属性的User。

我收到以下错误:

  1) User has a valid factory
     Failure/Error: expect(user).to be_valid
       expected #<User id: nil, fname: "first1", lname: "last1", created_at: nil, updated_at: nil> \
to be valid, but got errors: Account meta must exist

我正在使用Rails版本5.0.0beta1和Factory Girl 4.6.0。

我一直在与这一天作战 - 感谢你的帮助。

编辑:我看到使用rails控制台的行为相同,所以看起来这个问题与Factory Girl无关。

0 个答案:

没有答案