craig
craig

Reputation: 26262

URI::InvalidURIError not causing test to pass

I'm attempting to get a test to pass when an invalid URL is supplied:

it "is invalid when URL format is NOT valid" do
  entity = FactoryGirl.build(:entity, url: 'blah blah')
  expect(entity).to have(1).errors_on(:url)
end

But the test fails:

Failures:

1) Entity is invalid when url format is NOT valid
   Failure/Error: entity = FactoryGirl.build(:entity, url: 'blah blah')
   URI::InvalidURIError:
     bad URI(is not URI?): blah blah

It seems like the error isn't being raised in a way that it can be recognized by testing framework. What am I not understanding?

app/models/entity.rb:

require 'uri'
class Entity < ActiveRecord::Base

  validates :url, presence: true, uniqueness: true, :format => { :with => URI.regexp }

  ...

  def url=(_link)

    if _link
        uri = URI.parse(_link)

        if (!uri.scheme)
            link = "http://" + _link
        else
            link = _link
        end
      super(link)
    end

  end
end

spec/models/entity_spec.rb:

describe Entity do

  ...

  it "is invalid when url format is NOT valid" do
    entity = FactoryGirl.build(:entity, url: 'blah blah')
    expect(entity).to have(1).errors_on(:url)
  end

end

spec/factories/entity.rb:

FactoryGirl.define do
  factory :entity do
    name { Faker::Company.name }
    url { Faker::Internet.url }
  end
end

Upvotes: 0

Views: 555

Answers (1)

wpp
wpp

Reputation: 7303

It's been a while since I used Rspec, but I think you can try something like:

expect {
  FactoryGirl.build(:entity, url: 'blah blah')
}.to raise_error(URI::InvalidURIError)

Explanation, for question in comments

Whenever you call FactoryGirl.build(:entity, url: 'blah blah') the URI library will raise an exception (your error). The exception will be raised before you can assign it to the entity variable. Which causes the test to fail. The expect will all catch the exception and check if it is URI::InvalidURIError.

Upvotes: 1

Related Questions