2012-08-03 134 views
6

我一直在這個簡單的驗證上打破了我的頭,我無法得到驗證。我有以下型號:Rspec&FactoryGirl驗收驗證

class Attendance < ActiveRecord::Base 
    belongs_to :user, counter_cache: true 
    belongs_to :event, counter_cache: true 

    validates :terms_of_service, :acceptance => true 
end 

這是我廠:

factory :attendance do 
    user 
    event 
    terms_of_service true 
    end 

這是我的測試:

describe "event has many attendances" do 
    it "should have attendances" do 
     event = FactoryGirl.create(:event) 
     user1 = FactoryGirl.create(:user, firstname: "user1", email: "[email protected]") 
     user2 = FactoryGirl.create(:user, firstname: "user2", email: "[email protected]") 

     attendance1 = FactoryGirl.create(:attendance, event: event, user: user1, terms_of_service: true)  
    end 
    end 

這是不應該帶任何錯誤,但它確實。

Running spec/models/workshop_spec.rb 
.............F 

Failures: 

    1) Event event has many attendances should have attendances 
    Failure/Error: attendance1 = FactoryGirl.create(:attendance, event: event, user: user1, terms_of_service: true) 
    ActiveRecord::RecordInvalid: 
     Validation failed: Terms of service must be accepted 
    # ./spec/models/event_spec.rb:33:in `block (3 levels) in <top (required)>' 

當我在瀏覽器中執行這些操作時,我接受了一切順利。我在這裏錯過什麼?!

回答

9

:terms_of_service映射到db列嗎? validates :acceptance的默認值是字符串「1」,而不是true。 如果它映射到數據庫列,嘗試添加:accept => true來驗證:

validates :terms_of_service, :acceptance => {:accept => true} 

如果該字段沒有映射,或DB列不布爾,嘗試在測試和工廠使用「1」,而不是真正的。

+0

謝謝,就是這樣!我嘗試了一切,但一個字符串。謝謝,記錄它是一個虛擬屬性! – 2012-08-03 09:06:41

+0

@dimuch你有沒有知道你是我的英雄?謝謝。 – Jeff 2014-09-30 23:35:38