Answer
RequestSpecification and ResponseSpecification
These are reusable specification builders that let you define common request/response settings once and reuse them across all tests — following the DRY principle.
RequestSpecification
Defines common request settings: base URL, headers, auth, content type.
Java
import io.restassured.specification.RequestSpecification;
import io.restassured.builder.RequestSpecBuilder;
public class BaseTest {
protected static RequestSpecification requestSpec;
@BeforeClass
public static void buildRequestSpec() {
requestSpec = new RequestSpecBuilder()
.setBaseUri("https://api.example.com")
.setBasePath("/api")
.setContentType(ContentType.JSON)
.addHeader("Authorization", "Bearer " + getToken())
.addHeader("Accept", "application/json")
.setRelaxedHTTPSValidation()
.log(LogDetail.ALL)
.build();
}
}
Using RequestSpecification in tests:
Java
@Test
public void testGetUser() {
given(requestSpec) // ← reuse the spec
.pathParam("id", 2)
.when()
.get("/users/{id}")
.then()
.statusCode(200);
}
@Test
public void testCreateUser() {
given(requestSpec) // ← same spec, different endpoint
.body("{ \"name\": \"John\" }")
.when()
.post("/users")
.then()
.statusCode(201);
}
ResponseSpecification
Defines common response validations: status code, content type, response time.
Java
import io.restassured.specification.ResponseSpecification;
import io.restassured.builder.ResponseSpecBuilder;
public class BaseTest {
protected static ResponseSpecification responseSpec;
@BeforeClass
public static void buildResponseSpec() {
responseSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(2000L))
.expectHeader("Content-Type", containsString("application/json"))
.build();
}
}
Using ResponseSpecification in tests:
Java
@Test
public void testGetAllUsers() {
given(requestSpec)
.when()
.get("/users")
.then()
.spec(responseSpec) // ← reuse the response spec
.body("data.size()", greaterThan(0));
}
Combined Usage
Java
given(requestSpec)
.when()
.get("/users/1")
.then()
.spec(responseSpec)
.body("data.first_name", equalTo("Janet"));
Benefits
| Without Specs | With Specs |
|---|---|
| Repeat headers in every test | Define once, use everywhere |
| Inconsistent auth setup | Centralized auth management |
| Hard to update base URL | One-line change |
| Duplicated content-type | DRY (Don''t Repeat Yourself) |
