【问题标题】:Failing Rspec test of a FactoryGirl objectFactoryGirl 对象的 Rspec 测试失败
【发布时间】: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


    【解决方案1】:

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

    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')
    

    【讨论】:

    • 非常感谢!!!您推荐的代码更改成功了。我的 Rspec 测试现在是绿色的,我的应用程序代码按预期工作。顺便说一句,您假设我正在验证成员名字和姓氏的唯一性是正确的。 Rspec 测试从我的成员模型中获取了该参考。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多