Ruby on rails URI::InvalidURIError未导致测试通过
我试图在提供无效URL时通过测试:Ruby on rails URI::InvalidURIError未导致测试通过,ruby-on-rails,rspec,factory-bot,Ruby On Rails,Rspec,Factory Bot,我试图在提供无效URL时通过测试: 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
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
似乎错误并没有以测试框架可以识别的方式出现。我不明白什么
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
FactoryGirl.define do
factory :entity do
name { Faker::Company.name }
url { Faker::Internet.url }
end
end
spec/factories/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
FactoryGirl.define do
factory :entity do
name { Faker::Company.name }
url { Faker::Internet.url }
end
end
我已经有一段时间没有使用Rspec了,但我认为您可以尝试以下方法:
expect {
FactoryGirl.build(:entity, url: 'blah blah')
}.to raise_error(URI::InvalidURIError)
注释中的问题说明
无论何时调用
FactoryGirl.build(:entity,url:'blah blah')
the(您的错误)。在将异常分配给实体
变量之前,将引发该异常。这会导致测试失败。expect
将捕获异常并检查是否是URI::InvalidURIError
起作用,但为什么?当我尝试entity=FactoryGirl.build(:entity,url:'blah blah')
然后expect(entity)。要引发错误(URI::InvalidURIError)
,我得到了问题中列出的错误。嗨@craig,很高兴它成功了:)无论何时调用FactoryGirl.build(:entity,url:'blah blah')
URI库都会引发异常(您的错误)。在将该错误分配给实体
变量之前,将引发该错误。这会导致测试失败。好的,但是我对name
属性(validates:name,presence:true,university:true
)有类似的要求,该属性使用两行语法捕获。为什么不同?显然,它与:url
要求中的块有关。