Created
January 3, 2019 20:47
-
-
Save oreoshake/cf1263589c163fae44ae908baf05fa24 to your computer and use it in GitHub Desktop.
Just some examples of me using factory_bot wrong
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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