FactoryGirl对象的Rspec测试失败

时间:2014-12-30 19:43:15

标签: ruby-on-rails rspec factory-bot

我试图编写一个Rspec测试来评估模型中的验证,以防止健身房成员进行重复预约(即,与健身教练同一时间安排同一天)。我已经在我的应用程序中按预期运行了代码,但我仍然坚持如何为该方案编写有效的测试。

我的两个模型受到有关测试的影响:首先,有一个约会模型,属于成员和培训师。其次,有一个成员模型,其中包含有关健身房爱好者的个人资料信息。还有一个培训师模型,但是现在我只专注于为#&#34成员制定工作规范;会员不能重复预约"场景。我使用FactoryGirl gem创建测试数据。

这是我为#34;约会"所写的内容。 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的新手,非常感谢有关如何继续的任何建议,建议或想法。

1 个答案:

答案 0 :(得分: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')