2013-06-27 220 views
3

我正在使用Factory Girl和Faker創建獨特的測試用戶。 用戶模型在電子郵件上具有唯一性驗證。爲什麼Factory Girl在describe塊中調用時會創建重複對象

如果我嵌套2個描述塊的級別,那麼一些測試將失敗,因爲有重複的電子郵件。 如果我沒有嵌套描述塊,那麼所有的工廠調用都返回唯一的用戶並且測試通過。

爲什麼Faker在第一種情況下會生成重複的電子郵件?

#factories/user.rb 

# a simple factory with Faker 
FactoryGirl.define do 
    factory :student, class: User do 
    first_name { Faker::Name.first_name } 
    last_name { Faker::Name.last_name } 
    password { Faker::Lorem.words(3).join } 
    email { Faker::Internet.email } 
    end 
end 

#spec/models/user_spec.rb 

# in this test structure, Faker returns duplicate emails 
describe "nested describe blocks" do 
    describe "block 1" do 
    it "creates faker duplicates" do 
     10.times{ 
     FactoryGirl.create(:student) 
     } 
    end 
    end 
    describe "block 2" do 
    it "creates faker duplicates" do 
     10.times{ 
     FactoryGirl.create(:student) 
     } 
    end 
    end 
end 

# in this structure, Faker emails are unique 
describe "no nested describe blocks" do  
    it "doesn't create duplicates" do 
    10.times{ 
     FactoryGirl.create(:student) 
    } 
    end  
    it "doesn't create duplicates" do 
    10.times{ 
     FactoryGirl.create(:student) 
    } 
    end  
end 

Rspec的返回以下錯誤:

Failure/Error: FactoryGirl.create(:student) 
ActiveRecord::RecordInvalid: 
    Validation failed: Email has already been taken, Email has already been taken, Authentication token has already been taken 
+0

你介意發佈你的錯誤輸出嗎? –

+0

當然,我添加了它 – dyanisse

+0

我拿走了你的文件,並在我的機器上成功運行了它們,但是在這樣做的過程中,遇到了spork在後臺運行的問題,這使得我無法從中獲取更改工廠定義並導致您看到相同的驗證錯誤。這是一個很長的過程,但是當你運行測試時,你確定Rails沒有運行在其他進程中嗎?另外,我還以爲奇怪的是你有多個錯誤短語,用逗號分隔。你知道爲什麼嗎?最後,我建議在每次創建記錄後更改測試以打印電子郵件地址,以找到最佳答案。 –

回答

2

@Dyanisse正如你所說的,我們需要做下面的配置,spec_helper.rb

config.use_transactional_fixtures = true 

但只有是不夠的。我們需要將其添加在大括號重新評估其如下

auth_token { Faker::Lorem.characters(32) } 

它不會一起工作:

auth_token Faker::Lorem.characters(32) 
相關問題