2013-10-25 58 views
4

這是我的規格文件,當添加測試的上下文「不可更新的用戶平衡」我得到下面的錯誤。爲什麼這Rspec測試返回「電子郵件已經採取」

require 'spec_helper' 

describe Sale do 

    context 'after_commit' do 

    context 'assignable' do 
     sale = FactoryGirl.create(:sale, earned_cents: 10, assignable: true) 
     after { sale.run_callbacks(:commit) } 

     it 'updates user balance' do 
     sale.user.balance.should == sale.earned 
     end 
    end 

    context 'not assignable' do 
     sale = FactoryGirl.create(:sale, earned_cents: 10, assignable: false) 
     after { sale.run_callbacks(:commit) } 

     it 'does not updates user balance' do 
     sale.user.balance.should_not == sale.earned 
     end 
    end 

    end 
end 

而且工廠

require 'faker' 

FactoryGirl.define do 
    factory :user do 
    email Faker::Internet.email 
    password "mypassword" 
    end 

FactoryGirl.define do 
    factory :sale do 
    earned_cents 5 
    user 
    end 
end 

/spec/spec_helper.rb我也有過這樣

require 'database_cleaner' 
RSpec.configure do |config| 
    config.before(:suite) do 
    DatabaseCleaner.strategy = :transaction 
    DatabaseCleaner.clean_with(:truncation) 
    end 

    config.before(:each) do 
    DatabaseCleaner.start 
    end 

    config.after(:each) do 
    DatabaseCleaner.clean 
    end 
end 

這是我得到的錯誤。

`save!': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)

我猜它裏面Sale廠的user參考相關的,但我不知道爲什麼它不產生第二次測試新用戶或從數據庫中刪除。任何想法?

回答

14

在用戶的工廠,試試這個來代替:

factory :user do 
    email { Faker::Internet.email } 
    password "mypassword" 
end 
+7

是。工廠(:用戶)塊在定義工廠時運行,並不是每次創建記錄時都運行。因此,如果首次將'Factory :: Internet.email'評估爲「[email protected]」,那麼執行'email Faker :: Internet.email'就像做'email'foo @ bar.com''。 – kristinalim

+3

形成一個塊的大括號使這種電子郵件生成方法能夠在這種情況下多次重新運行。 – schwabsauce

+0

感謝@ kristinalim和@schwabsauce解釋爲什麼這個anwser是正確的;) – gfd

相關問題