Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 appropriate 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
like image 1000
Josh Glover Avatar asked Sep 03 '25 15:09

Josh Glover


2 Answers

What works in the later versions of FactoryBot is

FactoryBot.factories.registered?(name)
like image 66
Danny Avatar answered Sep 05 '25 06:09

Danny


From peeping at the latest:

FactoryGirl.find(name)

..should give you the factory.

This replaces the now deprecated:

FactoryGirl.factory_by_name(name)
like image 42
Mike Tunnicliffe Avatar answered Sep 05 '25 05:09

Mike Tunnicliffe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!