ruby-on-rails - 如何对多态属性进行 rspec 测试验证?
问题描述
我正在尝试我在 Rails 和 Rspec 中的第一个 TDD 项目。我终于得到了一些用于模型验证的简单样板 Rspec 代码。我的模型在和Employee
中具有多态关联。Email
Address
如何为这些多态关联编写验证?除了确保之外validates_presence_of :first_name, :last_name, :role
,我还想确保存在电子邮件和地址。
这是我的模型:
class Employee < ApplicationRecord
has_many :employee_projects
has_many :projects, through: :employee_projects
has_many :phones, as: :phonable, dependent: :destroy
has_many :emails, as: :emailable, dependent: :destroy
has_many :addresses, as: :addressable, dependent: :destroy
accepts_nested_attributes_for :emails, allow_destroy: true
validates_presence_of :first_name, :last_name, :role
end
class Address < ApplicationRecord
belongs_to :addressable, polymorphic: true
end
class Email < ApplicationRecord
belongs_to :emailable, polymorphic: true
end
这是我的 Rspec 测试Employee
:
require 'rails_helper'
RSpec.describe Employee, type: :model do
context 'Validation tests' do
subject { described_class.new(first_name: 'first_name', last_name: 'last_name', role: 'role')
}
it 'is valid with attributes' do
expect(subject).to be_valid
end
it 'is not valid without first_name' do
subject.first_name = nil
expect(subject).to_not be_valid
end
it 'is not valid without last_name' do
subject.last_name = nil
expect(subject).to_not be_valid
end
it 'is not valid without role' do
subject.role = nil
expect(subject).to_not be_valid
end
end
end
也希望开始使用 FactoryBot 但想先了解基础知识。
解决方案
推荐阅读
- php - 我的 php 代码运行,加载,但没有输出
- python - 在python中使用正则表达式在冒号或括号之前提取字符串
- css - 仅在 Safari 中转换动画的中断
- reactjs - React redux 和 React 路由器,链接更改不会重新渲染视图
- generics - 将参数传递给具有多个上限的泛型函数
- ruby-on-rails - 在 API 调用中生成 JSON 正文的正确语法
- windows - Uwp - 注册表值无效
- docker - 服务“侦听器”构建失败:docker compose
- apache-poi - 在 SpringBatch 中读取 XLSX 数据
- java - 如何使用线程将数据写入excel