ruby-on-rails - 代表 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
我尝试过创建一个教师,并在创建课程时使用它,但仍然很幸运。
我已经查看了如何处理工厂机器人和关系并尝试了一些,但我对测试太无知,无法让它工作。我希望能对我现在的情况有所了解。
解决方案
验证在保存时运行,您想要做的是使用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?
在幕后调用,这就是您要证明的。
推荐阅读
- sql - 是否可以将 array_agg 嵌套在另一个 array_agg 中
- jenkins - Zip Pipeline Utility - 递归压缩子目录和文件
- google-chrome-extension - Chrome 扩展后台脚本“无法访问 URL devtools 的内容...”错误?
- python - 如何使用specshow以对数刻度绘制频谱图?
- java - Eclipse 不会解析 LWJGL 参考 (.jar)
- c# - 如何在循环中执行其他工作时启动任务等待它
- .net-core - MSAL TokenAcquisition GetAccessTokenOnBehalfOfUser 始终失败,因为 getaccounts 始终为空
- graphql - GraphQL / Prisma 中的相同类型关系
- xslt-1.0 - 如何处理不同长度/更多“行”的文件
- github - 我无法使用 CircleCi 推送到 Github 中的分支“dev”