I am registering a request stub as follows:

url = "http://www.example.com/1"
stub_request(:get, url).
  with(body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n    <id>1</id>\n</project>\n",
       headers: {
         'Accept' => 'application/xml',
         'Content-type' => 'application/xml',
         'User-Agent' => 'Ruby',
         'X-Trackertoken' => '12345'
       }).
  to_return(status: 200, body: '', headers: {})

for some reason when I run bundle exec rspec spec, my specs fails saying that the request isn't registered yet. The registered stub is this,

stub_request(:get, "http://www.example.com/1").
  with(body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n    <id>1</id>\n</project>\n",
       headers: {
         'Accept' => 'application/xml',
         'Content-type' => 'application/xml',
         'User-Agent' => 'Ruby',
         'X-Trackertoken' => '12345'
       })

note that the to_return part is missing

I tried replacing the body header with an empty string, the request stub is registered correctly but then my specs will still fail because they are expecting some value from the body other than the empty string. Thus, it is really important that I assign a value to body.

In my spec I am calling this method:

def find(id)
  require 'net/http'
  http = Net::HTTP.new('www.example.com')
  headers = {
    "X-TrackerToken" => "12345",
    "Accept"         => "application/xml",
    "Content-type"   => "application/xml",
    "User-Agent"     => "Ruby"
  }
  parse(http.request(Net::HTTP::Get.new("/#{id}", headers)).body)
end

Any ideas on why this is happening?

Thanks.

有帮助吗?

解决方案

The problem is that your stub is matching a GET request with a non-empty body of <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n <id>1</id>\n</project>\n, but when you make the request you're not including any body, so it doesn't find the stub.

I think you're confused about what body is what here. The body in the with method arguments is the body of the request you are making, not the body of the response. What you probably want is a stub like this:

url = "http://www.example.com/1"
stub_request(:get, url).
  with(headers: {
         'Accept' => 'application/xml',
         'Content-type' => 'application/xml',
         'User-Agent' => 'Ruby',
         'X-Trackertoken' => '12345'
       }).
  to_return(status: 200,
            body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n    <id>1</id>\n</project>\n",
            headers: {})
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top