2

Here I use the attribute :new_record to set the condition for validation.

attr_accessor :new_record
validates :email, presence: true, email: true, unless: :new_record?

  def new_record?
    @new_record || true
  end

if the new_record? == true, the email validation will be skipped and new user is valid. I wrote this test: it { expect(subject).to validate_presence_of(:email) } and it returns error:

Failure/Error: it { expect(subject).to validate_presence_of(:email) }

       User did not properly validate that :email cannot be empty/falsy.
         After setting :email to ‹nil›, the matcher expected the User to be
         invalid, but it was valid instead.

Note that this test run perfectly if there is no condition added to the validation. Also, the code work well in production. I also have tried

    before(:each) do
      subject.new_record = true
    end

or

`before { allow(subject).to receive(:new_record?).and_return(true) }`

Can any one help?

Ian Tran
  • 315
  • 3
  • 14
  • `@new_record || true` will never return false. – yzalavin Feb 06 '18 at 16:01
  • I set the default new_record as true as default, when I need to create a new user and new_record as false when I need to edit the user profile. new_record == true this test should be passed if email is nil -> user.valid? == false. However, the result from test is "After setting :email to ‹nil›, the matcher expected the User to be invalid, but it was valid instead." – Ian Tran Feb 06 '18 at 16:06
  • Why don't u use `on: :create`? – yzalavin Feb 06 '18 at 16:11
  • That's a great idea instead of my new_record thing. However, I just try adding on: :create after `validates :email, presence: true, email: true, on: :create`. It failed with the same error. (Test passed before ading on: :create) – Ian Tran Feb 06 '18 at 16:22
  • You need also to change your spec for smth like this: `expect(subject).to validate_presence_of(:email).on(:create)`. – yzalavin Feb 06 '18 at 16:30
  • It works like a charm. Thank you a lot. – Ian Tran Feb 06 '18 at 16:51

0 Answers0