2012-08-03 53 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