开发者

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 ;)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜