我在Rails中很新,但我遇到的问题是:
当我输入以下代码时:
validates :ipaddress, :format => {
:with => Resolv::IPv4::Regex,
:message => 'Deve ser um endereco IP valido'
}
我的所有测试都没有问题。但是当我补充说:
validates :ipaddress, :format => {
:with => Resolv::IPv4::Regex,
:message => 'Deve ser um endereco IP valido'
}
validates :domain, :format => {
:with => URI.regexp,
:message => 'Deve ser um dominio valido'
}
测试开始失败并说:
F
Failure:
UrlTest#test_test_url_with_valid_IP_address
[/home/olegario/infracrawler/test/models/url_test.rb:7]:
Test a valid IP address.
Expected: true
Actual: false
bin/rails test test/models/url_test.rb:4
..F
Failure:
UrlTest#test_test_url_using_a_valid_domain [/home/olegario/infra-
crawler/test/models/url_test.rb:19]:
Test a valid domain.
Expected: true
Actual: false
为什么会这样?
修改
这是我的测试代码:
test 'test an url with a IP address containing characters' do
url = Url.new()
url.ipaddress = '192.168.2.AAA'
assert_equal(false, url.valid?, 'Test a invalid IP address')
end
test 'test url using a valid domain' do
url = Url.new()
url.domain = 'http://google.com'
assert_equal(true, url.valid?, 'Test a valid domain')
end
答案 0 :(得分:1)
您正在验证domain
和IP
这两者都不是一个。
即使您提供了有效的IP地址,IP地址的第一次测试也会失败并返回false。
我认为正确的测试应如下所示
test 'test an url with a IP address containing characters' do
url = Url.new()
url.ipaddress = '192.168.2.AAA'
url.domain = 'http://google.com'
assert_equal(false, url.valid?, 'Test a invalid IP address')
end
test 'test url using a valid domain' do
url = Url.new()
url.ipaddress = '192.168.2.1'
url.domain = 'http://google.com'
assert_equal(true, url.valid?, 'Test a valid domain')
end
答案 1 :(得分:1)
您的测试方法和有关验证的假设是错误的。 .valid?
方法运行模型中的所有验证。生成的错误将添加到模型实例中的错误哈希中。如果错误哈希为空,则返回true(有效),否则为false。
因此,通过声明.valid?
为真/假来测试验证是容易出错的,因为每个测试都必须考虑其他所有验证。
要单独测试单个验证,您应该编写有关错误哈希的断言:
test 'test an url with a IP address containing characters' do
url = Url.new(ipaddress: '192.168.2.AAA')
url.valid? # runs the validations
assert_true(url.errors.has_key?(:ipaddress))
assert_contains(url.errors][:ipaddress], 'Deve ser um endereco IP valido')
end
test 'test an url with a valid ip' do
url = Url.new(ipaddress: '192.168.2.1')
url.valid? # runs the validations
assert_false(url.errors.has_key?(:ipaddress))
end