Rspec 如何避免Factory Girl对象的持久性
我有几个rspec测试使用工厂女孩。它在MongoDB上与Rails 3应用程序中的MongoId一起使用 在此过程中,我针对无效值进行了测试:预期会出现验证错误。之后,无论何时我调用Rspec 如何避免Factory Girl对象的持久性,rspec,persistence,factory-bot,Rspec,Persistence,Factory Bot,我有几个rspec测试使用工厂女孩。它在MongoDB上与Rails 3应用程序中的MongoId一起使用 在此过程中,我针对无效值进行了测试:预期会出现验证错误。之后,无论何时我调用工厂(:user),它都会因为验证错误而失败。当我调用工厂(:user)时,我希望得到一个全新的、干净的对象,而不是一个重复使用的、破旧的对象 下面的示例代码演示了*user_spec.rb*向“角色”添加无效项。用户模型成功地将记录标记为无效 在规范中,一个*sidebar\u helper\u spec.rb*
工厂(:user)
,它都会因为验证错误而失败。当我调用工厂(:user)时,我希望得到一个全新的、干净的对象,而不是一个重复使用的、破旧的对象
下面的示例代码演示了*user_spec.rb*向“角色”添加无效项。用户模型成功地将记录标记为无效
在规范中,一个*sidebar\u helper\u spec.rb*需要实例化一个@user
,它失败了,告诉我无效的角色“foo”在那里。但是您可以清楚地看到,factory.rb中不存在此角色
这是预期的行为吗?我可以用配置选项切换持久性(或缓存)吗
## models/user_spec.rb
require 'spec_helper'
describe User do
describe 'roles' do
before(:each) do
@user = Factory.build(:user)
end
it 'should require a role' do
@user.roles = nil
@user.should_not be_valid
end
it 'should allow one role from set of defined roles' do
#@user.roles is preset in factory with "jobseeker"
@user.should be_valid
end
it 'should reject undefined roles' do
@user.roles << "foo"
@user.should_not be_valid
end
it 'should allow multiple roles' do
@user.roles = ["banned", "jobseeker"]
@user.should be_valid
end
end
end
## helpers/sidebar_helper_spec.rb
require 'spec_helper'
describe SidebarHelper do
before(:each) do
@user = Factory.create(:user) #fails with Mongoid::Errors::Validations: Validation failed - Roles foo is an invalid role.
@profile = Factory.create(:profile)
end
# Has many specs, but all Fail on error in the before(:each)
end
## Actual factory.rb
Factory.define :user do |f|
f.password 'mischief managed'
f.email 'h.potter@gryffindor.hogwards.edu.wiz'
f.roles ['jobseeker']
end
Factory.define :employer do |f|
f.password 'butterscotch'
f.email 'dumbledore@staff.hogwards.edu.wiz'
f.roles ['employer']
end
Factory.define :profile do |f|
f.available true
f.sync false
end
##型号/用户规格.rb
需要“spec\u helper”
描述用户做什么
描述“角色”是什么
在…之前做
@user=Factory.build(:user)
结束
它“应该需要一个角色”吗
@user.roles=nil
@user.u不应该是有效的
结束
它“应该允许一组已定义角色中的一个角色”do
#@用户角色在工厂中预设为“求职者”
@user.u应该是有效的
结束
它“应该拒绝未定义的角色”
@user.roles=
创建一个新数组[“禁止”,“求职者”]
,并将其设置为@user.roles
:
# should allow multiple roles
@user.roles = ["banned", "jobseeker"]
但是
# should reject undefined roles
@user.roles << "foo"
Factory.define :user do |f|
...
f.roles { ['jobseeker'] }
end
Factory.define :employer do |f|
...
f.roles { ['employer'] }
end
# should reject undefined roles
@user.roles = [ "foo" ]