我有经过以下验证的User
模型,并且正在使用Shoulda Matchers Gem(这是该方法的确切页面):
validates_inclusion_of :birthday,
:in => Date.new(1850)..Time.now.years_ago(13).to_date,
:message => 'Sorry, you must be at least 13 years old to join.'
我用的是FactoryGirl和Rspec。我对我的User
型号进行了以下测试:
describe "valid user age" do
it { should ensure_inclusion_of(:birthday).in_range(13..150) }
end
FactoryGirl.define do
factory :user do
sequence(:first_name) { |n| "Bob#{n}" }
sequence(:last_name) { |n| "User#{n}" }
email { "#{first_name}@example.com" }
birthday { Date.today - 13.years }
password "foobarbob"
end
end
现在,从所有这些我得到了错误:
User valid user age
Failure/Error: it { should ensure_inclusion_of(:birthday).in_range(13..150) }
Did not expect errors to include "is not included in the list" when birthday is set to 12, got error:
为什么在浏览器中测试时会出现这种情况?
should匹配器除了检查值的范围外,还检查错误消息。如果您查看发布的链接中的实现,您将看到低消息和高消息都默认为:include(用于查找标准rails错误消息的国际化版本的符号)。
允许值匹配器中的错误消息检查允许将预期消息指定为符号、正则表达式或字符串。
您在验证中使用的范围也与测试中使用的不同(日期范围与int范围)。我相信如果你把它改成,你的考试就会通过
it { should ensure_inclusion_of(:birthday).in_range(Date.new(1850)..Time.now.years_ago(13).to_date).with_message(/must be at least 13/) }