0

I'm very new in Rails, and I have the following problem. I have this class Url that has its own validations:

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

I have another class Link that has an Url. The validations are:

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

But the problem is when I run this test:

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

The test says that everything is okay, but the validation of the URL is not occurring. How can I force Rails to validate the URL too?

Halil Özgür
  • 15,731
  • 6
  • 49
  • 56
olegario
  • 711
  • 2
  • 16
  • 35
  • 1
    you are not validating the `Url` in this case maybe take a look at [`validates_associated`](http://api.rubyonrails.org/v5.1/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated) – engineersmnky Sep 20 '17 at 18:07
  • engineersmnky was right to point out that what you want is validating the URL associated with the link, which in this case is just an instance of `Url` with no data. I'd like to add that you could add the following assertion to enforce the proper association `assert_true link.url.valid?` – oxfist Sep 20 '17 at 18:17
  • @Oxfist that assumes a guaranteed binding between `link` and `url` if a link can exist without a `url` then that assertion is error prone. – engineersmnky Sep 20 '17 at 18:31
  • 1
    @engineersmnky that is true but given the context of the question and the test code provided that could be a valid solution to properly validate the `Url` instance. – oxfist Sep 20 '17 at 19:28
  • Thanks @engineersmnky that exactly I was looking for. Please answer the question so I can give the credits to you. – olegario Sep 20 '17 at 21:14

0 Answers0