ruby – 已定义FactoryGirl继承属性

前端之家收集整理的这篇文章主要介绍了ruby – 已定义FactoryGirl继承属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好吧,伙计们.这怎么有意义呢?两个嵌套工厂(被FactoryGirl视为继承)不应相互冲突.到底他妈发生了什么?要么它不是继承,要么它是.我不知道为什么他们会把它称为继承,如果不是的话.我只是做错了吗? (注意f.account_type)

看看下面的工厂定义.

factory :partner do |f|
  f.company_name { Faker::Company.name }
  f.username { Faker::Internet.user_name }
  f.password { Faker::Internet.password }
  f.password_confirmation { password }
  f.pid { Faker::Lorem.word }

  f.association :primary_contact

  # Inherited
  factory :business_partner do
    f.account_type "business"
    f.tax_id { Faker::Company.duns_number }
  end

  # Inherited
  factory :personal_partner do
    f.account_type "personal"
    f.ssn { Faker::Company.duns_number }
  end

end

当我运行我的测试时,我收到此错误.

Failure/Error: partner = FactoryGirl.create(:business_partner)
  FactoryGirl::AttributeDefinitionError:
    Attribute already defined: account_type

而且为了完整性,我的规格.

# spec/models/partner.rb
require 'spec_helper'
require 'pp'

describe Partner do

  it "has a valid factory" do
    partner = FactoryGirl.create(:business_partner)
    partner.should be_valid
    puts partner
  end

  it "is invalid without a firstname" do
#    FactoryGirl.build(:partner_contact,first_name: nil).should_not be_valid
  end

  it "is invalid without a lastname" do
#    FactoryGirl.build(:partner_contact,last_name: nil).should_not be_valid
  end

  it "is invalid without an email address" do
#    FactoryGirl.build(:partner_contact,email: nil).should_not be_valid
  end

  #it "returns a contact's fullname as a string"

end

解决方法

在business_partner和personal_partner工厂定义中,您指的是f,它是合作伙伴工厂的定义.这意味着,即使account_type定义出现在子工厂中,也都在父工厂中定义.

在较新版本的FactoryGirl中修复此问题的最简单方法是完全删除块参数.

factory :partner do
  company_name { Faker::Company.name }
  username { Faker::Internet.user_name }
  password { Faker::Internet.password }
  password_confirmation { password }
  pid { Faker::Lorem.word }

  association :primary_contact

  # Inherited
  factory :business_partner do
    account_type "business"
    tax_id { Faker::Company.duns_number }
  end

  # Inherited
  factory :personal_partner do
    account_type "personal"
    ssn { Faker::Company.duns_number }
  end
end

如果您喜欢块参数,只需确保接受每个工厂定义的参数并使用不同的变量名称.

原文链接:https://www.f2er.com/ruby/268356.html

猜你在找的Ruby相关文章