rspec webmock to_raise错误没有引发错误

时间:2018-01-07 13:10:07

标签: ruby rspec webmock

我有以下代码段和测试

class Service
  def self.status(base_uri = 'localhost', basic_auth = {})
    base_uri = "#{ base_uri }/status"
    response = HTTParty.get(base_uri, basic_auth: basic_auth)
  rescue StandardError => e
    binding.pry
    raise "Error occured code: #{ response.code } msg: #{ e.message }"
  end
end
it 'should return error msg if url is not valid' do
  bad_url = "http://bar_url.com"
  expected = 'Error occured'
  stub_request(:get, bad_url).
            with(headers: {'Authorization'=>'Basic YWRtaW46YWRtaW4='}).
            to_raise(StandardError)

  expect { Service.status(bad_url, { username: @username, password: @password }) }.to raise_error(/#{ expected }/) 
end 

此代码基于documentation 因此,rspec总是引发异常:

expected /Error occured/, got #<WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. Unregistered request: GET h...rization'=>'Basic YWRtaW46YWRtaW4='})

任何人都可以帮我弄清楚我应该改变什么来获得StandardError作为结果吗?

1 个答案:

答案 0 :(得分:3)

由于服务调用"#{ base_uri }/status" http://bar_url.com/statusstub_request仅使用http://bar_url.com声明,因此Net :: HTTP.Get会查找与此匹配,而不是http://bar_url/status
这就是测试中没有错误提升的原因。