Skip to content

Find or Factory method for tests

February 1, 2011

Rails comes with a nice method called find_or_create which, as you might imagine, looks for an object given certain parameters, and if no such object exists, it creates the object.

But I rarely use that method, because I would much rather create objects in Factories during my tests. And then sometimes my tests complain that the object I’m trying to create already exists. FML

So today I wrote a new helper method to fix the problem, namely, find_or_factory

(Put this in your test_helper)


def find_or_factory(model, attributes)
..model_as_constant = model.to_s.titleize.gsub(' ', '').constantize
..object = model_as_constant.where(attributes).first
..object ||= Factory.create(model.to_sym, attributes)
..object
end

Now you can write:

@study = find_or_factory(:study, :name => "Default Study")

From → Uncategorized

Leave a Comment

Leave a comment