【发布时间】:2018-07-09 18:51:20
【问题描述】:
鉴于模型设置如下:
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) 课程在期间和师资独特时有效 失败/错误: course = create(:course)
ActiveRecord::RecordInvalid: Validation failed: Faculty must exist
我尝试过创建一个教师,并在创建课程时使用它,但仍然很幸运。
我已经查找了如何处理工厂机器人和关系并尝试了其中一些,但我对测试太无知,无法让它发挥作用。我希望能对我现在的情况有所了解。
【问题讨论】:
-
我回答你的问题了吗?
标签: ruby-on-rails testing rspec factory-bot