如何在保存Rails之前验证对象?

时间:2017-09-20 17:28:47

标签: ruby-on-rails ruby validation testing

我在Rails中非常新,我有以下问题。我有这个类Url,它有自己的验证:

class Url
  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'
  }
end

我有另一个Link的班级Url。验证是:

class Link
  validates :path, :format => {
    :with => /\A[\S]+\Z/,
    :message => 'Deve conter uma path valida'
  }
end

但问题是当我运行此测试时:

test 'test a link with a valid path' do
  link = Link.new()
  link.url = Url.new()
  link.path = 'this/is/my/favorite/path'
  assert_equal(true, link.valid?, 'Test a valid path')
end

测试表明一切正常,但未验证URL。我怎样才能强制Rails验证URL呢?

0 个答案:

没有答案