sherbert sherbert - 1 year ago 52
Ruby Question

Using FactoryGirl without Rails, ActiveRecord or any database with RSpec

I was wondering if anyone knows whether it's possible to use FactoryGirl without any of the aforementioned prerequisites.

I would like to use it to generate on-the-fly test data when driving UI automation tests for both mobile and web, and even possibly API.

I know I could create some custom helper classes/methods and use getters and setters, etc., but I thought it would be good to use this awesome little gem.

I have searched quite extensively and also tried to set up a basic RSpec project (I also tried Cucumber), but to no avail. It still appears that I need classes to be instantiated with the relevant login in order to consume it.

FactoryGirl.define do
factory :user do
firstname { Faker::Name.first_name }
lastname { Faker::Name.last_name }
age { 1 + rand(100) }

Then if I try to call it in a RSpec file...

user = build_stubbed(:user)

I have also read the docs and tried all the other variants, I just keep getting...

Failure/Error: user = build_stubbed(:user)
uninitialized constant User

which suggests I need a class called User with all the logic.

Answer Source

Your surmise is correct -- you still have to write the User class yourself. factory_girl works fine with non-ActiveRecord classes, but it doesn't write them for you.

By default factory_girl constructs instances by calling new with no parameters, so your class should either not def initialize or initialize must take no parameters, just like an ActiveRecord model. So the easiest thing to do would be to write User like so:

class User
  attr_accessor :firstname, :lastname, :age

If you decide you need an initialize that requires parameters, you can use factory_girl's initialize_with to tell it how to instantiate your class.