【发布时间】:2014-12-30 19:43:15
【问题描述】:
我正在尝试编写 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 新手,如果有任何关于如何继续的建议、建议或想法,我将不胜感激。
【问题讨论】:
标签: ruby-on-rails rspec factory-bot