Shoulda validate_format_of . not_with has problem in framework (or in my understanding)
Asked Answered
H

3

10

I put the following code into an RSpec test:

it { should validate_format_of(:email).not_with('test@test')}

and setup the actual class with:

validates :email, :presence => true, :format => /\b[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i

And when I run the tests I get:

Failures: 1) User Failure/Error: it { should validate_format_of(:email).not_with('test@test')} Expected errors to include "can't be blank" when email is set to "test@test", got errors: ["name can't be blank (nil)", "email is invalid (\"test@test\")"] # ./spec/models/user_spec.rb:8:in `block (2 levels) in '

When I do a passing test like:

it { should validate_format_of(:email).with('[email protected]')}

Everything works as expected. Can someone tell me if I'm doing something wrong or if this is a framework problem. Thank you.

Hypnotism answered 9/11, 2010 at 13:58 Comment(1)
Assuming you meant 'test@test' for the failing test value, correct?Strahan
S
28

Try this instead:

it { should_not allow_value("test@test").for(:email) }
Strahan answered 9/11, 2010 at 22:26 Comment(0)
M
3

I just ran into a similar problem Turns out you need to invoke the with_message method and supply the exact error message as a string, or a regex that matches the error message. Doing so will convince the validate_format_of to cease its stubborn insistence that format errors result in "can't be blank" messages, and actually pass. For example:

it { should validate_format_of(:email).not_with('test@test')}

becomes

it { should validate_format_of(:email).not_with('test@test').with_message(/invalid/)}

This sure looks like a bug in the shoulda library.

Mccallum answered 15/3, 2011 at 18:54 Comment(1)
Also note that you need to invoke with_message on "with" cases as well, or else it'll errantly succeed because it's looking for "cant be blank" in the error list of the field being validated.Mccallum
L
1

From Shouda Matchers 2.0, validate_format_of was deprecated. Please use allow_value.

should validate_format_of(:email).with('[email protected]')

to

should allow_value('[email protected]').for(:email )

from thoughtbot blog: https://thoughtbot.com/blog/shoulda-matchers-2-0#validate_format_of

Lectionary answered 3/7, 2022 at 5:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.