我正在创建一个与数据库交互的GUI应用程序,因此我需要对我的RSpec测试进行夹具管理.我使用sqlite数据库,我将编写一个将使用直接SQL操作数据的类.我需要测试它的数据库交互功能.
当我运行RSpec测试时,我找不到任何可以执行两项基本操作的库:
已经有成千上万的博客文章和手册清楚地解释了如何将FactoryGirl与任何版本的Rails一起使用,但没有人没有它.我开始挖掘,这就是我所拥有的(请注意,我不使用rails及其组件):
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
Run Code Online (Sandbox Code Playgroud)
spec/factories.rb:
Factory.define :note do |f|
f.body 'body of a note'
f.title 'title of a note'
end
Run Code Online (Sandbox Code Playgroud)
lib/note.rb:
class Note
attr_accessor :title, :body
end
Run Code Online (Sandbox Code Playgroud)
当我跑步时,rspec -c spec/note_spec.rb我得到以下:
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)>'
Run Code Online (Sandbox Code Playgroud)
问题:
Note从特定类继承我的类,因为FactoryGirl正在寻找save!方法?我是Ruby/RSpec/BDD的新手,所以任何帮助都将不胜感激;)
Mic*_*ley 10
默认情况下,factory_girl会创建保存的实例.如果您不想将对象保存到数据库,则可以使用该build方法创建未保存的实例.
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
Run Code Online (Sandbox Code Playgroud)
请参阅入门文件中的"使用工厂" .