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?