0
我第一次嘗試使用異常和自定義驗證器。 當我把這個begin ... end
放入單獨的文件中時,它可以工作,但是對於我在rspec中的簡單測試,它不會。自定義URI驗證器不起作用
這裏是我的模型的驗證網址:
validates_each :url do |record,attr,value|
begin
!!URI.parse(value)
rescue URI::InvalidURIError
record.errors.add(attr, 'invalid url format')
end
end
rspec的(我到這裏來的有效,應爲無效):
describe Entry do
before do
@entry = Entry.new(title: "Post Title", url: "http://google.com", content: "lorem ipsum")
end
subject {@entry}
it {should be_valid}
(other tests)
describe "when url has wrong format" do
it "should be invalid" do
invalid_urls = %w[^net.pl p://yahoo.com]
invalid_urls.each do |url|
@entry.url = url
@entry.should_not be_valid
end
end
end
end
我把它放在單獨的文件中的應用程序/驗證/ uri_format_validator.rb
class UriFormatValidator < ActiveModel::EachValidator
def validate_each(record,attribute,value)
URI.parse(value)
rescue URI::InvalidURIError
record.errors[attribute] << "is not an URL format"
end
end
仍然不起作用,這很有趣,因爲我試着用單獨的文件,它的工作KS精細輸出FALSE壞網址:
require 'uri'
begin
URI.parse("http://onet!!t.pl")
rescue URI::InvalidURIError
puts "FALSE"
end
我試了一下,但沒有工作:( –
兩件事情:1),這取決於你把自定義驗證器,例如也許在'apps/lib'中,你可能需要重新啓動rails服務器,並且2)運行'rails console'並創建一個新的Entry實例,添加一個僞造的URL和'save'實例 - 將測試本身隔離爲一個可能的原因。 –