Offer advice for association typo
Closes https://github.com/thoughtbot/factory_bot/issues/1227 In this code we are passing an implicit declaration `user`, rather than the symbol `:user`: ```rb factory :post do author factory: user end ``` In https://github.com/thoughtbot/factory_bot/issues/1227 we improved the error message from: ```rb undefined method 'name' for :post:Symbol ``` to: ```rb Trait not registered: user ``` But this still doesn't make it totally obvious what the error was. Why are we trying to register a user trait? With this PR we update the error message to: ```rb Association 'author' received an invalid factory argument. Did you mean? 'factory: :user' ```
This commit is contained in:
parent
197947fc73
commit
041216d250
|
@ -22,9 +22,20 @@ module FactoryBot
|
|||
private
|
||||
|
||||
def build
|
||||
ensure_factory_is_not_a_declaration!
|
||||
|
||||
factory_name = @overrides[:factory] || name
|
||||
[Attribute::Association.new(name, factory_name, [@traits, @overrides.except(:factory)].flatten)]
|
||||
end
|
||||
|
||||
def ensure_factory_is_not_a_declaration!
|
||||
if @overrides[:factory].is_a?(Declaration)
|
||||
raise ArgumentError.new(<<~MSG)
|
||||
Association '#{name}' received an invalid factory argument.
|
||||
Did you mean? 'factory: :#{@overrides[:factory].name}'
|
||||
MSG
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -9,8 +9,11 @@ describe "associations" do
|
|||
end
|
||||
end
|
||||
|
||||
expect { FactoryBot.build(:post) }.
|
||||
to raise_error(KeyError, "Trait not registered: \"user\"")
|
||||
expect { FactoryBot.build(:post) }.to raise_error(
|
||||
ArgumentError,
|
||||
"Association 'author' received an invalid factory argument.\n" \
|
||||
"Did you mean? 'factory: :user'\n",
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue