URI :: InvalidURIError不导致测试通过

时间:2014-07-01 20:35:45

标签: ruby-on-rails rspec factory-bot

我正在尝试在提供无效网址时通过测试:

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

但测试失败了:

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

似乎错误没有被测试框架识别出来。我不理解的是什么?

应用程序/模型/ 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

规格/模型/ 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

规格/工厂/ entity.rb:

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

1 个答案:

答案 0 :(得分:1)

我使用Rspec已经有一段时间了,但我认为你可以尝试类似的东西:

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

解释,对于评论中的问题

每当您致电FactoryGirl.build(:entity, url: 'blah blah')URI library will raise an exception(您的错误)。在将其分配给entity变量之前,将引发异常。这导致测试失败。 expect将全部捕获异常并检查它是否为URI::InvalidURIError