Some really useful SpecFlow steps when testing REST API's

Hackered
Sunday, August 10, 2014
by Sean McAlinden

I have written the following steps quite a few times now so this post is really a new home for me to copy and paste. The steps rely on the use of RestSharp, the Should library and the fact that you have stored the last response in the scenario context. The code utilises my ScenarioContextService class.

[Then("the status code should be '(.*)'")]
public void TheStatusCodeShouldEqual(int statusCode)
{
    var lastResponse = ScenarioContextService.GetValue();
    lastResponse.StatusCode.ShouldEqual((HttpStatusCode)statusCode);
}

[Then("the response reason phrase should be '(.*)'")]
public void TheReasonPhraseShouldEqual(string expectedReasonPhrase)
{
    var lastResponse = ScenarioContextService.GetValue();
    lastResponse.StatusDescription.ShouldEqual(expectedReasonPhrase);
}

[Then(@"the body should include '(.*)'")]
public void ThenTheBodyShouldInclude(string includedText)
{
    var lastResponse = ScenarioContextService.GetValue();
    lastResponse.Content.ShouldNotBeNull("Body should not be null");
    lastResponse.Content.ShouldContain(includedText, StringComparison.OrdinalIgnoreCase);
}

[Then(@"the body should not include '(.*)'")]
public void ThenTheBodyShouldNotInclude(string excludedText)
{
    var lastResponse = ScenarioContextService.GetValue();
    lastResponse.Content.ShouldNotContain(excludedText, StringComparison.OrdinalIgnoreCase);
}