Checking the Response

Rack::Test provides the last_response method for checking HTTP responses. Add the following line inside your spec, right after the post request:

 expect​(last_response.status).to eq(200)

You’ve encountered code like this before, in Your First Spec. It’s an expectation fulfilling the role an assertion method would play in other test frameworks.

Together, expect() and to() check a result in order to signal success or failure. They compare a value—in this case, the HTTP status code returned by last_response.status—using a matcher. Here, we create a matcher using the eq method, which indicates whether or not the value wrapped by expect equals the provided argument of 200. When we pass the matcher from eq(200) as an argument to the to() method, we’ll get a passing or failing result.

This may seem like a lot of moving parts compared to a traditional assertion-style method like assert_equal. Matchers are, however, more powerful and more composable than traditional assertions. We’ll see more about them in Chapter 10, Exploring RSpec Expectations.

Let’s look at what happens when we run this code:

 $ ​​bundle exec rspec
 F
 
 Failures:
 
  1) Expense Tracker API records submitted expenses
  Failure/Error: expect(last_response.status).to eq(200)
 
  expected: 200
  got: 404
 
  (compared using ==)
 
  truncated

Our app is returning a 404 (Not Found) status code. That’s not surprising; we haven’t added any routes to the Sinatra code yet. Go ahead and do so now:

 post ​'/expenses'​ ​do
 end

When you rerun your specs, you should see a passing result.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset