Bypass Rails validations when creating FactoryGirl objects

maxenglander picture maxenglander · Oct 4, 2011 · Viewed 11.5k times · Source

I have two models (ModelA and ModelB), and FactoryGirl factories for each. I want the factory for ModelB to be able to (A) create test data, and to (B) build (without saving to database) sample data for display to customers. I am having trouble getting (A) to work due to Rails validations in my models.

ModelA:

class ModelA < ActiveRecord::Base
  belongs_to :model_b
  validates_presence_of :model_b
end

Factory for ModelA:

FactoryGirl.define do
  factory :model_a do
    some_attr "hello"
    model_b { FactoryGirl.build :model_b }
  end
end

ModelB

class ModelB < ActiveRecord::Base
  has_one :model_a
end

Factory for ModelB

FactoryGirl.define do
  factory :model_b do
    some_attr "goodbye"
  end
end

I can't create objects from these factories without getting validation errors:

 ruby> FactoryGirl.create :model_a
 ActiveRecord::RecordInvalid: Validation failed: ModelB can't be blank

It appears that FactoryGirl is attempting to save the factory object before saving its assocations. I realize that I could have the factory for ModelB create its associated ModelA (rather than build it) - however, then I would lose the flexibility of being able to use the ModelA factory to either build sample data or save test data. Alternately, I could remove the validations; but then I wouldn't have validations.

Any other options?

Answer

Houen picture Houen · Dec 22, 2013

How about this?

FactoryGirl.build(:model_a).save(validate: false)

EDIT: As Scott McMillin comments below, if you want the built object as a variable, you can to do this:

model_a = FactoryGirl.build(:model_a)
model_a.save(validate: false)