Integrating Error Status Codes for a Microservice with TDD
In this guide we'll implement RSpec tests to ensure that the application renders the appropriate error message when the record is not created in the database.
Guide Tasks
  • Read Tutorial

Right now we have a request spec that tests to ensure that the application will create new Notification when send the appropriate JSON data via the API. However we don't have any tests in place to ensure that the application will respond with an appropriate error message when something goes wrong. Providing error messages is vital when building out an API since other developers working with the service need to know when an error has occurred. In fact, many times applications that connect to APIs build their entire systems with the expectation that their will receive either a success or failure message from services that they connect to, so this is an important feature to have working properly.

In our last micorservice guide we actually implemented a conditional in the create controller action that will respond with an appropriate unprocessable_entity response, so our test should actually pass immediately.

We're going to create another request spec that will leave out the required source_app parameter from the JSON data, which will trigger a validation error. So let's create the spec:

# spec/requests/notification_spec.rb

  it 'renders an error status if the notification was not created' do
    headers = {
      "ACCEPT" => "application/json"

    post "/notifications",
      notification: {
        phone: "5555555555",
        body: "My Message"
    }, headers

    expect(response.content_type).to eq("application/json")
    expect(response).to have_http_status(:unprocessable_entity)

If you run rspec you'll see that all of the tests are passing and now we can be confident that other applications connecting to our API will be able to create records and if any errors occur they will be notified of the issue.


I'm not sure if you've noticed, however our test suite is missing some very important test cases such as users passing messages that are too long or invalid phone numbers, so in the next guide will implement these validations to ensure that only valid data will be passed through the API.