首页 > 解决方案 > 代表 has_many :though with Factory Bot

问题描述

鉴于模型设置如下:

class Course < ApplicationRecord
  belongs_to :faculty
  has_many :teachings
  has_many :faculty, through: :teachings

  validates :name, uniqueness: { scope: [:faculty_id, :period,
                                         :semester, :year] }
end

class Faculty < ApplicationRecord
  has_secure_password

  has_many :courses
  has_many :courses, :through => :teachings

  validates :email, { presence: true, uniqueness: true }
  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :password, presence: true
end

我正在尝试像这样测试课程的创建:

RSpec.describe Course, :type => :model do

  it "is valid with when period and faculty are unique" do
    course = create(:course)
    expect(course).to be_invalid
  end
end

运行测试时出现以下错误:

1)课程有效,期间和教师是唯一的失败/错误:课程=创建(:课程)

 ActiveRecord::RecordInvalid:
   Validation failed: Faculty must exist

我尝试过创建一个教师,并在创建课程时使用它,但仍然很幸运。

我已经查看了如何处理工厂机器人和关系并尝试了一些,但我对测试太无知,无法让它工作。我希望能对我现在的情况有所了解。

标签: ruby-on-railstestingrspecfactory-bot

解决方案


验证在保存时运行,您想要做的是使用build.

  it "is valid with when period and faculty are unique" do
    course = build(:course, faculty: create(:faculty))
    expect(course).to be_invalid
  end

这将course.valid?在幕后调用,这就是您要证明的。


推荐阅读