如何在工厂中使用’sequence’来避免使用’FactoryGirl.reload’?
必须使用FactoryGirl.reload
可能会花费一些开销来运行所有测试(当存在许多测试时),并且它也被描述为反模式 。
如何继续使用唯一字段的排序,然后测试正确的值?
你可以在我的代码中看到……
-
我必须调用
FactoryGirl.reload
以便在任何先前的测试已经运行的情况下,增量从1
开始。 -
我必须声明
:count => 1
因为只有一个该值的实例。
规格/工厂/ clients.rb
FactoryGirl.define do factory :client do name "Name" sequence(:email} { |n| "email#{n}@example.com" } sequence(:username) { |n| "username#{n}" } end end
规格/客户/ index.html.erb_spec.rb
require 'spec_helper' describe "clients/index" do before do FactoryGirl.reload (1..5).each do FactoryGirl.create(:client) end @clients = Client.all end it "renders a list of clients" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Name".to_s, :count => 5 assert_select "tr>td", :text => "email1@example.com".to_s, :count => 1 assert_select "tr>td", :text => "username1".to_s, :count => 1 end end
如何为这个特定的测试传递特殊名称?
require 'spec_helper' describe "clients/index" do before do (1..5).each do |num| FactoryGirl.create(:client, username: "special#{num}") end @clients = Client.all end it "renders a list of clients" do render assert_select "tr>td", :text => "special1".to_s, :count => 1 end end
添加到mind.blank的答案…如果您希望测试增量值,也可以将它们放在增量循环中。
it "renders a list of clients" do render (1..5).each do |num| assert_select "tr>td", :text => "special#{num}".to_s, :count => 1 end end