2014-12-30 77 views
1

我正在尝试编写一个Rspec测试来评估模型中的验证,以防止健身房成员进行重复约会(即,安排同一时间,同一天与健身教练)。我的代码在我的应用程序中按预期工作,但我坚持如何为该方案编写有效的测试。FactoryGirl对象的失败Rspec测试

我的两个模型都受到了有关测试的影响:首先,有一个委任模型,属于成员和培训者。其次,有一个会员模型,其中包含关于健身者的个人资料信息。还有一个教练模型,但现在我只关注于获取“成员不能有重复约会”场景的工作规范。我使用FactoryGirl gem创建测试数据。

这里就是我的“约会” Rspec的测试写:

it "is invalid when a member has a duplicate appointment_date" do 
FactoryGirl.create(:appointment, appointment_date: "2015-12-02 00:09:00") 
appointment = FactoryGirl.build(:appointment, appointment_date: "2015-12-02 00:09:00") 
appointment.valid? 
expect(appointment.errors[:member]).to include('has already been taken')  
end 

我的约会模式包含以下内容:

belongs_to :member 
belongs_to :trainer 

validates :member, uniqueness: {scope: :appointment_date} 
validates :trainer, uniqueness: {scope: :appointment_date} 

我创建了下面的工厂进行预约,会员:

FactoryGirl.define do 
    factory :appointment do 
    appointment_date "2015-01-02 00:08:00" 
    duration 30 
    member 
    trainer  
    end 
end 

FactoryGirl.define do 
    factory :member do 
    first_name "Joe" 
    last_name "Enthusiast" 
    age 29 
    height 72 
    weight 190 
    goal "fffff" * 5 
    start_date "2014-12-03" 
    end 
end 

注:我也有一个教练工厂。

当我运行Rspec的测试,它会生成以下错误:

Failure/Error: appointment = FactoryGirl.build(:appointment, appointment_date:   "2015-12-02 00:09:00") 
ActiveRecord::RecordInvalid: 
Validation failed: First name has already been taken, Last name has already been taken 

看来Rspec的有,我试图建立第二FactoryGirl对象有问题,但我不明白我需要什么要解决这个问题。我是Rails的新手,希望对如何继续进行任何建议,建议或想法。

回答

0

在创建两个约会时,您还创建了两个相同的member,这显然违反了您对成员不具有相同名字和/或姓氏的某些规则。 最好的解决办法是建立一个成员

single_member = FactoryGirl.create(:member) 

,然后实例成员传递到您的FactoryGirl任命实例,以便它,而不是使用您的会员对象,而不是重新创建。

FactoryGirl.create(:appointment, appointment_date: "2015-12-02 00:09:00", member: single_member) 
appointment = FactoryGirl.build(:appointment, appointment_date: "2015-12-02 00:09:00", member: single_member) 
appointment.valid? 
expect(appointment.errors[:member]).to include('has already been taken') 
+1

非常感谢!你推荐的代码更改是有用的。我的Rspec测试现在是绿色的,我的应用程序代码按预期工作。顺便说一句,你是正确的,假设我正在验证成员姓名的唯一性。 Rspec测试从我的成员模型中挑选出该参考。再次感谢您! – codeinspired