我正在尝试编写一个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很陌生,希望能就如何继续工作提出任何建议、建议或想法。
发布于 2014-12-30 20:34:16
在创建两个约会时,您还创建了两个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')
https://stackoverflow.com/questions/27711533
复制相似问题