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/trait.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

31 lines
639 B
Ruby

module FactoryBot
# @api private
class Trait
attr_reader :name, :definition
def initialize(name, &block)
@name = name.to_s
@block = block
@definition = Definition.new(@name)
proxy = FactoryBot::DefinitionProxy.new(@definition)
proxy.instance_eval(&@block) if block_given?
end
delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor,
:callbacks, :attributes, to: :@definition
def names
[@name]
end
def ==(other)
name == other.name &&
block == other.block
end
protected
attr_reader :block
end
end