내가 사용한 시퀀스는 공장에서 소녀를 얻는 유일한 값을 가지만 나는 유효성 검사 오류

StackOverflow https://stackoverflow.com/questions/2474158

  •  21-09-2019
  •  | 
  •  

문제

나는 모델 정의 이 방법

class Lga < ActiveRecord::Base
  validates_uniqueness_of :code
  validates_presence_of :name
end 

나는 정의된 공장에 대한 Lgas 과

Factory.sequence(:lga_id) { |n| n + 10000 }

Factory.define :lga do |l|
  id = Factory.next :lga_id
  l.code "lga_#{id}"
  l.name "LGA #{id}"
end

그러나,실행

Factory.create(:lga)
Factory.create(:lga)

script/console

>> Factory.create(:lga)
=> #<Lga id: 2, code: "lga_10001", name: "LGA 10001", created_at: "2010-03-18  23:55:29", updated_at: "2010-03-18 23:55:29">
>> Factory.create(:lga)
ActiveRecord::RecordInvalid: Validation failed: Code has already been taken
도움이 되었습니까?

해결책

문제는 그 것입니다 code 그리고 name 속성은 소위 호출되지 않았습니다 게으른 속성. 나는 다음과 같은 글을 쓰는 것을 생각했다.

Factory.define :lga do |l|
  l.code { |n| "lga_#{n+10000}" }
end

그러나 나는 ID를 재사용하고 싶었다 name 속성도. 당신은 보장 할 수 있습니다 id 매번 평가됩니다 Factory.create 그것을 넣어서 호출됩니다 after_build 훅.

Factory.define :lga do |l|
   l.after_build do |lga|
     id = Factory.next :lga_id
     lga.code = "lga_#{id}"
     lga.name = "LGA #{id}"
   end
end

이것은 FactoryGirl 1.2.3 이상에서만 작동합니다.

다른 팁

이전 대답은 여전히 올바르지만 새로운 버전에서의 FactoryGirl 을 경고를 얻을 수 있습니다.

Factory.next has been depreciated. Use FactoryGirl.generate instead.

새 코드는 다음과 같습니다:

Factory.define :lga do |l|
   l.after_build do |lga|
     id = FactoryGirl.generate :lga_id
     lga.code = "lga_#{id}"
     lga.name = "LGA #{id}"
   end
end

출처: http://notesofgreg.blogspot.co.uk/2012/07/foolproof-factorygirl-sequence.html

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top