应该 validate_format_of 。 not_with 在框架中有问题(或者在我的理解中)
我将以下代码放入 RSpec 测试中:
it { should validate_format_of(:email).not_with('test@test')}
并使用以下命令设置实际的类:
validates :email, :presence => true, :format => /\b[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i
当我运行测试时,我得到:
失败: 1)用户 失败/错误:它 { 应该 validate_format_of(:email).not_with('test@test')} 当电子邮件设置为“test@test”时,预期错误包括“不能为空”,收到错误:[“名称不能为空(nil)”,“电子邮件无效(\“test@test\” )"] # ./spec/models/user_spec.rb:8:in `block (2 level) in '
当我进行如下测试时:
it { should validate_format_of(:email).with('[email protected]')}
一切都按预期工作。有人可以告诉我我是否做错了什么或者这是一个框架问题。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
Try this instead:
我刚刚遇到了类似的问题原来你需要调用
with_message
方法并以字符串形式提供确切的错误消息,或与错误消息匹配的正则表达式。这样做将说服 validate_format_of 停止顽固地坚持格式错误会导致“不能为空”消息,并真正通过。例如:变得
这看起来确实像是shoulda库中的一个错误。
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:becomes
This sure looks like a bug in the shoulda library.
从 Shouda Matchers 2.0 开始,validate_format_of 已被弃用。请使用
allow_value
。来自
thoughtbot博客:https://thoughtbot.com/blog/shoulda-matchers -2-0#validate_format_of
From Shouda Matchers 2.0, validate_format_of was deprecated. Please use
allow_value
.to
from thoughtbot blog: https://thoughtbot.com/blog/shoulda-matchers-2-0#validate_format_of