Can I ask Factory Girl if a given factory exists?
I have a series of models for which I've defined factories. I also have an API-based model which subclasses ActiveResource::Base
, which I (apparently) cannot build from a factory--I get an exception when Factory Girl calls FooAPI.new
.
I've instead defined a Foo
class in test/lib
. What I'd like to do in my test is see if a factory exists for a given symbol (e.g. :foo
, :bar
, etc.), then fall back to attempting to directly construct an object of the appropriate class, using String#classify.constantize
. Here's my current clunky implementation:
objects[name] = begin
klass = name.to_s.classify.constantize
klass.new
rescue
Factory.build name
end
I'd prefer something like this:
Factory.exists?(name) ? Factory.build(name) : name.to_s.classify.constantize.new
That way, I'd get an ap开发者_StackOverflow社区propriate exception on a failure to construct an object.
Update: Thanks to fd, I found a way to do this without exception handling!
objects[name] = if Factory.factories.include?(name)
Factory.build name
else
klass = name.to_s.classify.constantize
klass.new
end
What works in the later versions of FactoryBot is
FactoryBot.factories.registered?(name)
From peeping at the latest:
FactoryGirl.find(name)
..should give you the factory.
This replaces the now deprecated:
FactoryGirl.factory_by_name(name)
Having thought about it for an hour, I realised that this:
objects[name] = Factory.exists?(name) ? Factory.build(name) : name.to_s.classify.constantize.new
is really not different from this:
objects[name] = begin
Factory.build name
rescue ArgumentError => e
raise unless e.message == "No such factory: #{name}"
name.to_s.classify.constantize.new
end
So I think I'll just go with that. :)
精彩评论