Factory Girl - Rails fixture 的完全替代工具

[url=http://www.pmamediagroup.com/2009/04/tutorial-install-rspec-rails-factory-girl/]另外一个Rspec和Factory Girl的用法示例[/url]
I think you all know that, when using fixtures in your test, you keep switching between files to see what fixtures there are, always struggling with dependencies and conflicts.

There are a couple of helpers that solve this, but this is the best one I came across until know: Factory Girl

As the names says, it provides some kind of factory for your objects and instances.

The following snippet illustrates the definition of such a factory:


# define an incremental username
Factory.sequence :user do |n|
"user#{n}"
end

# define a user factory
Factory.define :user do |u|
u.admin false
u.username { Factory.next(:user) } # lazy loaded
end

# define a project factory with associated user
Factory.define :project do |p|
p.title 'myproject'
p.creator {|a| a.association(:user) } # again lazy loaded
end


Now, this factory can be used in your tests:


it "should do something" do
Factory.create(:user) # creates a user
Factory(:user) # creates another user (note the shortcut)
@u = Factory.build(:user, :username => 'customuser') # only build, no save
Factory.create (:project, :creator => @u)
end


I think you get the basic idea behind it, it’s actually pretty clean and makes tests a lot more readable without looking at fixtures.

Note: At the time of this writing, the attribute name does not work since there is a conflict (that will be resolved soon). Instead you have to use:


Factory.define :project do |p|
p.add_attribute :name, "myname"
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值