I have a model that requires a valid format of a URL.
class Event < ActiveRecord::Base
validates_format_of :url, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
end
BUT BEFORE implementing the solution I want to write a test that fails. Is this how someone would go about writing a failed test? (Please no Rspec or Shoulda solution trying to stick with basics before going to advanced testing / matcher frameworks.
class EventTest < ActiveSupport::TestCase
setup do
# These attributes are valid
@event_attributes = { :title => "A title",
:url => "http://somedomain.com/images/land.jpg",}
end
test "should not be valid with an INVALID URL" do
@event = Event.new(@event_attributes.merge(:url => "htp:/domain"))
assert_no_match(/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix, @event.url, "Not a valid format")
end
end
Is the assert_no_match the right approach. Any suggestions.
It’s not the right approach, because you’re not testing
Eventvalidation at all. Instead, a common pattern is to create an object with an attribute that will trigger the validation error and assert that the validation exception has been raised. So, in your case:Rspec is good, so you should try it at some point, and better sooner than later, I think. Also there is a nice library for the
@event_attributes.mergepattern you’ve used: it’s called factory_girl. Check it out, it will save you some trouble.