mr_muscle
mr_muscle

Reputation: 2900

RSpec for email format validation failed

I've got user devise model with validations

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

and RSpec file to test email validation

describe 'email field' do
  subject { User.new(first_name: 'jan', last_name: 'kowalski', email: '[email protected]').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

I want to test the validations for correct email address format which is in user model. Every test passed well except the last where I have an error expected: true got: false. Did I miss something in a spec file? or maybe I have wrong declaration in user model? Any helps are welcomed.

Upvotes: 1

Views: 898

Answers (1)

Luis Silva
Luis Silva

Reputation: 201

you have some mistakes in your spec file, the two let of email are not execution in anyway.

if you want that behavior you need to replace the email option in your subject by a variable, and your second it you need to wrap it in a context and put inside you let(:email), this is the way that rspec is going to replace the value of your subject in each it.

Here an example but using a password variable, also your two first test are passing, because your are missing the password that way your expec is false, but they are not test the test your are describing.

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

Upvotes: 2

Related Questions