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?

5
  • 1
    you are not validating the Url in this case maybe take a look at validates_associated Commented Sep 20, 2017 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? Commented Sep 20, 2017 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. Commented Sep 20, 2017 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. Commented Sep 20, 2017 at 19:28
  • Thanks @engineersmnky that exactly I was looking for. Please answer the question so I can give the credits to you. Commented Sep 20, 2017 at 21:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.