【问题标题】:RSpec for email format validation failed电子邮件格式验证的 RSpec 失败
【发布时间】:2018-11-22 18:09:07
【问题描述】:

我有带有验证的用户设计模型

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  validates :first_name, presence: true, length: { maximum: 100 }
  validates :last_name, presence: true, length: { maximum: 100 }
  validates :email, presence: true, uniqueness: true, format: { with: /\A.+@.+\..+\z/ }
end

和用于测试电子邮件验证的 RSpec 文件

describe 'email field' do
  subject { User.new(first_name: 'jan', last_name: 'kowalski', email: 'jan@foo.com').valid? }

  context 'when email has wrong format' do
    let(:email) { 'jan@foo' }

    it 'complains for invalid format' do
      is_expected.to eq false
    end

    let(:email) { 'jan' }

    it 'complains for invalid format' do
      is_expected.to eq false
    end
  end

  context 'when email has correct format' do

    it 'accepts valid format' do
      is_expected.to eq true
    end
  end
end

我想测试用户模型中正确电子邮件地址格式的验证。除了最后一次出现错误expected: true got: false 之外,每项测试都顺利通过。我错过了规范文件中的某些内容吗?或者我在用户模型中有错误的声明?欢迎任何帮助。

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    您的规范文件中有一些错误,电子邮件的两个 let 无论如何都没有执行。

    如果你想要这种行为,你需要用一个变量替换你的主题中的电子邮件选项,然后你需要将它包装在一个上下文中并放入你的 let(:email),这就是 rspec 的方式将替换每个主题中的主题值。

    这是一个示例,但使用密码变量,您的两个第一个测试也通过了,因为您丢失了密码,您的预期为假,但他们没有测试您描述的测试。

    describe 'password field' do
      subject { Usuario.new(nombre: 'jan', username: 'kowalski', password: password).valid? }
    
      context 'when password has wrong format' do
        let(:password) { nil }
        it 'complains for invalid format' do
          is_expected.to eq false
        end
      end
    
      context 'when password size is incorrect' do
        let(:password) { 'jan' }
        it 'complains for invalid format' do
          is_expected.to eq false
        end
      end
    
      context 'when password has correct format' do
        let(:password) { '1qaz2wsx' }
        it 'accepts valid format' do
          is_expected.to eq true
        end
      end
    end
    

    【讨论】:

    • 您的示例向我展示了我忘记添加设计模型中所需的密码。当然,解决方案也是用变量替换电子邮件选项。
    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 2015-06-15
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    相关资源
    最近更新 更多