Factory_bot: Forced creating of an invalid record

Created on 12 Nov 2013  路  8Comments  路  Source: thoughtbot/factory_bot

Hello, is there any standart way to create an invalid record using factory girl.

First thing, of course is to use:
let(:var) { FactoryGirl.build :factory_name, ... }
before { var.save(validate: false) }

But maybe there is some pretty looking syntax for using FactoryGirl.create ?

Most helpful comment

Using this technique inside traits seems to work.

trait :pay do
  # Turn off validation so we can create order with pay status directly
  to_create {|instance| instance.save(validate: false) }
  status "pay"
end

All 8 comments

@shaggyone you can use custom methods to persist objects:

factory :different_orm_model do
  to_create {|instance| instance.save(validate: false) }
end

But this way you always will save that factory objects skipping validations. It would be nice to have a way to define multiple creation methods, or simply be able to provide some argument to to_create. In my case, I only want to skip validations in some tests.

Thanks!

Does this work?

factory :user do
  factory :user_skips_validate do
    to_create {|instance| instance.save(validate: false) }
  end
end

FactoryGirl.create(:user, username: "valid_username")
FactoryGirl.create(:user_skips_validate, username: "invalid username -!@#$%^&*-=")

Yeah, surely it works... but I usually like to have one factory per model, and just provide ways to have fined control over it through traits. But surely this is just my workflow and your proposal should be 100% acceptable. Thanks.

Using this technique inside traits seems to work.

trait :pay do
  # Turn off validation so we can create order with pay status directly
  to_create {|instance| instance.save(validate: false) }
  status "pay"
end

what about forcing to save record, column_validation not in model.
PG::NotNullViolation: ERROR: null value in column "not_null_column_here" violates not-null constraint

is it still possible?

@aldrienht You can't ignore or disable constraints in Postgres. If you really want to test with a nil value, you can use build_stubbed and mocks to simulate getting a nil result. However, given that it's impossible in your database, I can't think of why you'd want to model this in your tests.

trait :skip_validate do
  to_create {|instance| instance.save(validate: false) }
end
Was this page helpful?
0 / 5 - 0 ratings