1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00
thoughtbot--factory_bot/lib/factory_bot/factory_runner.rb
Daniel Colson 6078d8c486 Improve error message for resolving invalid traits
Fixes [#1259]
Fixes [#1267]

In [#1156] we added support for looking up local traits with either a
symbol or string. This matches the lookup for factories and for global
traits.

We were calling `to_sym` on the trait arguments passed in when
building an object, assuming that those arguments would always respond
to `to_sym`. This leads to a confusing error message when passing an
object that doesn't respond to that method.

This PR replaces the confusing "NoMethodError: undefined method `to_sym`
for ..." with a more helpful "KeyError: Trait not registered: ...". It
ensures that all trait resolution is done using strings instead of
symbols, all objects should have a `to_s` method.

Co-authored-by: Sean Doyle <sean.p.doyle24@gmail.com>

[#1259]: https://github.com/thoughtbot/factory_bot/issues/1259
[#1267]: https://github.com/thoughtbot/factory_bot/issues/1267
[#1156]: https://github.com/thoughtbot/factory_bot/pull/1156
2019-02-22 16:08:38 -05:00

33 lines
824 B
Ruby

module FactoryBot
class FactoryRunner
def initialize(name, strategy, traits_and_overrides)
@name = name
@strategy = strategy
@overrides = traits_and_overrides.extract_options!
@traits = traits_and_overrides
end
def run(runner_strategy = @strategy, &block)
factory = FactoryBot.factory_by_name(@name)
factory.compile
if @traits.any?
factory = factory.with_traits(@traits)
end
instrumentation_payload = {
name: @name,
strategy: runner_strategy,
traits: @traits,
overrides: @overrides,
factory: factory,
}
ActiveSupport::Notifications.instrument("factory_bot.run_factory", instrumentation_payload) do
factory.run(runner_strategy, @overrides, &block)
end
end
end
end