Skip to content

Instantly share code, notes, and snippets.

@oreoshake
Created January 3, 2019 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oreoshake/cf1263589c163fae44ae908baf05fa24 to your computer and use it in GitHub Desktop.
Save oreoshake/cf1263589c163fae44ae908baf05fa24 to your computer and use it in GitHub Desktop.
Just some examples of me using factory_bot wrong
# Traits can be used as implicit factory attributes but if a value is set in a
# a factory, a trait cannot override that value. If you explicitely pass the trait,
# it overrides as expected.
require 'factory_bot'
FactoryBot.define do
factory :foobot do
foo { "parent" }
override
trait :override do
foo { "not actually an override" }
end
end
end
puts FactoryBot.build(:foobot).foo # expected "not actually an override", got "parent"
puts FactoryBot.build(:foobot, :override).foo # "not actually an override", as expected
# But if no value is set in the parent things work as expected
FactoryBot.define do
factory :foobot2, class: "Foobot" do
# foo { "parent" }
override
trait :override do
foo { "technically not an override bc no default value" }
end
end
end
puts FactoryBot.build(:foobot2).foo # technically not an override bc no default value
puts FactoryBot.build(:foobot2, :override).foo # technically not an override bc no default value
# Implicit traits in factories cannot override transient attributes default values
require 'factory_bot'
class Foobot
attr_accessor :foo
end
FactoryBot.define do
factory :foobot do
asdfify
trait :asdfify do
asdf { false }
end
factory :asdfify2 do
asdf { false }
end
transient do
asdf { true }
end
after(:build) do |foo, evaluator|
puts evaluator.asdf
end
end
end
puts FactoryBot.build(:foobot) # true, like the default (implicit trait ignored)
puts FactoryBot.build(:foobot, :asdfify) # false, like the trait override
puts FactoryBot.build(:asdfify2) # false, like the factory override
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment