2011-05-13 52 views
2

我在factories.rb中有這個設置。factory_girls序列和唯一性

Factory.sequence(:email) { |n| "email#{n}@factory.com" } 
Factory.sequence(:username) { |n| "username_#{n}" } 

Factory.define :user do |u| 
    u.email { Factory.next :email } 
    u.username { Factory.next :username } 
    u.first_name 'Ivan' 
    u.last_name 'Pupkin' 
    u.latitude '42' 
    u.longitude '-71' 
    u.password 'qwerty' 
    u.password_confirmation 'qwerty' 
end 

當我創建兩個工廠實例(:用戶)我得到唯一性錯誤。

describe CartsController do 

    let(:user) { Factory(:user) } 
    let(:another_user) { Factory(:user) } 
    let(:cart) { Factory(:cart) } 


    describe 'show my cart' do 
    before { sign_in user} 
    before { get :show, :id => user.carts.last } 
    it { should respond_with :success } 
    end 

    describe 'show different person cart' do 
    before { sign_in user } 
    before { get :show, :id => another_user.carts.last} 
    it { should respond_with :redirect } 
    end 
end 

我的問題在哪裏?

Failure/Error: let(:user) { Factory(:user) } 
Validation failed: Username has already been taken, Email has already been taken 

回答

3

似乎有在你的數據庫記錄,因爲失敗let(:user) { Factory(:user) }而不是let(:another_user) { Factory(:user) }所以我看到了兩個可能的解決方案:在頂部或手動清潔DB添加User.delete_all

1

啊,這是在測試數據庫剩菜。你應該有以下行spec_helper.rb

config.use_transactional_fixtures = true 

注意,即使您正在使用的工廠,而不是燈具是非常有用的。它將每個示例包裝在數據庫事務中,以便每次都有一個乾淨的平板。如果您沒有使用ActiveRecord,或者由於其他原因導致事務不能爲您工作,則需要在每次測試運行後清理一下像database_cleaner gem之類的東西來清理測試數據庫。