Is it a bad idea to write invalid FactoryGirl factories/traits?
factory-bot, rspec2, ruby-on-rails, traits, unit-testing
Solution
No it's not a good idea, it wont make your specs clear to understand after a while, and later when your code evolve those factory that fail today may not fail anymore, and you would have hard time to review all your specs.
It is way better to write your test for one clearly identified thing. If you want to check that saving fails with a mandatory parameter missing, just write it with your regular factory and add parameters to overwrite the values from the factory:
it 'should fail' do
create :winner, user_extension: nil
...
end
Problem
Listening to Giant Robots Smashing Into Other Giant Robots podcast, I heard that you want your FactoryGirl factories to be minimal, only providing those attributes that make the object valid in the database. That being said, the talk also went on to say that traits are a really good way to define specific behavior based on an attribute that may change in the future. I'm wondering if it's also a good idea to have traits defined that purposefully fail validations to clean up the spec code. Here's an example: ``` factory :winner do user_extension "7036" contest_rank 1 contest trait :paid do paid true end trait :unpaid do paid false end trait :missing_user_extension do user_extension nil end trait :empty_user_extension do user_extension "" end end ``` will allow me to call `build_stubbed(:winner, :missing_user_extension)` in my specs in tests I intend to fail validations. I suppose I could further this explicit fail by nesting these bad factories under another factory called `:invalid_winner`, but I'm not too sure if that's necessary. I'm mostly interested in hearing others' opinions on this concept.