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/spec/support/matchers/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

11 lines
260 B
Ruby

RSpec::Matchers.define :have_trait do |trait_name|
match do |instance|
instance.defined_traits.any? do |trait|
trait.name == trait_name.to_s && trait.send(:block) == @block
end
end
chain :with_block do |block|
@block = block
end
end