galymzhan
galymzhan

Reputation: 5523

Is it possible to use FactoryGirl without Rails?

I'm creating a GUI application which interacts with database so I need fixture management for my RSpec tests. I use sqlite database and am going to write a class which will manipulate data with straight SQL. I need to test it's database interaction functionality.

I couldn't find any libraries which could do 2 basic things when I run RSpec tests:

  1. Clear database or particular tables in it
  2. Load specific data into it so I can use that data in my tests

There are already ten thousands of blog posts and manuals which clearly explain how to use FactoryGirl with any version of Rails but no one without it. I started digging around and this is what I have (note that I don't use rails and it's components):

spec/note_spec.rb:

require 'spec_helper'
require 'note'

describe Note do
  it "should return body" do
    @note = Factory(:note)
    note.body.should == 'body of a note'
  end
end

spec/factories.rb:

Factory.define :note do |f|
  f.body 'body of a note'
  f.title 'title of a note'
end

lib/note.rb:

class Note
  attr_accessor :title, :body
end

When I run rspec -c spec/note_spec.rb I get following:

F

Failures:

  1) Note should return body
     Failure/Error: @note = Factory(:note)
     NoMethodError:
       undefined method `save!' for #<Note:0x8c33f18>
     # ./spec/note_spec.rb:6:in `block (2 levels) in <top (required)>'

Questions:

  1. Is it possible at all to use FactoryGirl without Rails and Rails libraries like ActiveModel/ActiveRecord?
  2. Do I have to subclass my Note class from particular class, since FactoryGirl is looking for save! method?
  3. Are there any other more viable solutions besides FactoryGirl?

I'm totally new to Ruby/RSpec/BDD, so any help will be greatly appreciated ;)

Upvotes: 3

Views: 4271

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159105

By default factory_girl creates saved instances. If you don't want to save the object to the database, you can create unsaved instances using the build method.

require 'spec_helper'
require 'note'

describe Note do
  it "should return body" do
    @note = Factory.build(:note)
    note.body.should == 'body of a note'
  end
end

See "Using Factories" in the Getting Started file.

Upvotes: 10

Related Questions