Rails: Avoiding duplication errors in Factory Girl…am I doing it wrong?

前端 未结 4 951
花落未央
花落未央 2021-01-31 16:00

Suppose I have a model user, which has a uniqueness constraint on the email field

If I call Factory(:user) once all is well, but i

4条回答
  •  梦毁少年i
    2021-01-31 16:17

    Here's what I do to force the 'n' in my factory girl sequence to be the same as that object's id, and thereby avoid collisions:

    First, I define a method that finds what the next id should be in app/models/user.rb:

    def self.next_id
      self.last.nil? ? 1 : self.last.id + 1
    end 
    

    Then I call User.next_id from spec/factories.rb to start the sequence:

    factory :user do
      association(:demo)
      association(:location)
      password  "password"
      sequence(:email, User.next_id) {|n| "darth_#{n}@sunni.ru" }
    end
    

提交回复
热议问题