不增加工厂女孩序列(Factory Girl sequences not incrementing)

2019-06-26 05:47发布

我试图让FactoryGirl产生一些名字对我来说,但该序列似乎并没有增加。

# spec/factories/vessel.rb
require 'factory_girl'
FactoryGirl.define do

  sequence :vessel_name do |n|
    "TK42#{n}"
  end

  factory :vessel do
    name FactoryGirl.generate(:vessel_name)
    vessel_type 'fermenter'
    volume_scalar 100.0
    volume_units 'bbl'
  end
end

# spec/models/vessel_spec.rb
require 'spec_helper'

describe Vessel do

  context 'working in the factory' do

    it 'makes a valid vessel' do
      vessel = FactoryGirl.create(:vessel)
      vessel.should be_valid, "Invalid vessel #{vessel.valid? || vessel.errors.messages.inspect}"
    end

    it 'makes another valid vessel' do
      vessel = FactoryGirl.create(:vessel)
      vessel.should be_valid, "Invalid vessel #{vessel.valid? || vessel.errors.messages.inspect}"
    end

  end

end

该规范输出

Vessel
  working in the factory
    makes a valid vessel
    makes another valid vessel (FAILED - 1)

Failures:

  1) Vessel working in the factory makes another valid vessel
     Failure/Error: vessel = FactoryGirl.create(:vessel)
     ActiveRecord::RecordInvalid:
       Validation failed: Name has already been taken
     # ./spec/models/vessel_spec.rb:13:in `block (3 levels) in <top (required)>'

# app/models/vessel.rb
class Vessel < ActiveRecord::Base

  attr_accessible :name, :vessel_type, :volume_scalar, :volume_units

  validates :name, :presence => true, :uniqueness => true

end

0 HAL:0 work/nrb-brewery-management % bundle show factory_girl_rails rspec
/home/brundage/.rvm/gems/ruby-1.9.3-p0/gems/factory_girl_rails-3.5.0
/home/brundage/.rvm/gems/ruby-1.9.3-p0/gems/rspec-2.11.0

0 HAL:0 work/nrb-brewery-management % rails c test
Loading test environment (Rails 3.2.6)
1.9.3p0 :001 > FactoryGirl.generate :vessel_name
 => "TK422" 
1.9.3p0 :002 > FactoryGirl.generate :vessel_name
 => "TK423" 
1.9.3p0 :003 > FactoryGirl.generate :vessel_name
 => "TK424" 
1.9.3p0 :004 > FactoryGirl.generate :vessel_name
 => "TK425" 

为什么不FactoryGirl产生在我的规范名称的序列?

Answer 1:

这样的作品,咬它意味着你不能在任何地方的规格覆盖名字,因为构建钩后会一直运行并覆盖任何名称。

你原来的例子不工作的原因是,你调用序列定义出厂的时候,而不是在工厂运行时。 你可以提供一个块的属性将在每个工厂运行时调用的定义。 这样,你有机会产生价值为每个实例,而不是生成所有实例的一个值。 这是最常用的序列和时间。

您可以在这个片段中解决您的原来的例子:

sequence :vessel_name do |n|
  "TK42#{n}"
end

factory :vessel do
  name { generate(:vessel_name) }
  vessel_type 'fermenter'
  volume_scalar 100.0
  volume_units 'bbl'
end

如果所有的名称可以用相同的格式生成,你也可以离开了价值完全通过重命名你的序列:

sequence :name do |n|
  "TK42#{n}"
end

factory :vessel do
  name
  vessel_type 'fermenter'
  volume_scalar 100.0
  volume_units 'bbl'
end

但是,如果你需要不同的名称,格式不同的工厂,将无法正常工作。



Answer 2:

答案是:

require 'factory_girl'

FactoryGirl.define do

  sequence :vessel_name do |n|
    "TK42#{n}"
  end

  factory :vessel do
    vessel_type 'fermenter'
    volume_scalar 100.0
    volume_units 'bbl'
    after :build do |v|
      v.name = FactoryGirl.generate(:vessel_name)
    end
  end
end


文章来源: Factory Girl sequences not incrementing