首页 > 解决方案 > 如何对多态属性进行 rspec 测试验证?

问题描述

我正在尝试我在 Rails 和 Rspec 中的第一个 TDD 项目。我终于得到了一些用于模型验证的简单样板 Rspec 代码。我的模型在和Employee中具有多态关联。EmailAddress

如何为这些多态关联编写验证?除了确保之外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 但想先了解基础知识。

标签: ruby-on-railstddrspec-railspolymorphic-associations

解决方案


推荐阅读