0

私は初めて例外とカスタムバリデーターを試してみました。これをbegin ... end別のファイルに入れると機能しますが、rspec での単純なテストでは機能しません。

これが私のモデルのURL検証です:

  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

別のファイルapps/validators/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

それでも機能しません。別のファイルで試してみたのは面白い原因であり、正常に機能し、悪いURLに対してFALSEを出力します。

require 'uri'

begin
  URI.parse("http://onet!!t.pl")
rescue URI::InvalidURIError
  puts "FALSE"
end
4

1 に答える 1

0

カスタムバリデーターはサブクラス化する必要があり、メソッドActiveModel::EachValidatorを持つ必要があると思います。validate_each

class AllGoodValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    if <some-test-that-fails-the-validation>
      object.errors[attribute] << (options[:message] || "is not all good")
    end
  end
end

これは、次のような他の通常の検証とともにモデルで使用できます

  validates :something, :presence => true, :all_good => true
于 2012-11-19T20:18:47.393 に答える