So let’s combine our routes and run the test via test on the sbt console. Click on the Run button of the SPA widget given at the bottom of the lesson, and wait for the environment to set up. We pull a docker image with the pre-configured environment to save you the hassle of setting up the environment on your own.
Once set up, you will need to perform the following steps:
Step-1: Start the database
First, start the PostgreSQL database within the container. We can do that by using the following command:
1
service postgresql start
Start PostgreSQL
Step-2: Execute the tests
Once the database is up, you can execute all the tests by using the following command:
1
xxxxxxxxxx
/*
* CC0 1.0 Universal (CC0 1.0) - Public Domain Dedication
*
final class ProductsRoutesTest extends BaseSpec {
implicit def decodeProduct: EntityDecoder[IO, Product] = jsonOf
implicit def decodeProducts: EntityDecoder[IO, List[Product]] = jsonOf
implicit def encodeProduct[A[_]: Applicative]: EntityEncoder[A, Product] = jsonEncoderOf
implicit val contextShift: ContextShift[IO] = IO.contextShift(global)
implicit val timer: Timer[IO] = IO.timer(global)
private val emptyRepository: Repository[IO] = new TestRepository[IO](Seq.empty)
"ProductsRoutes" when {
"GET /products" when {
"no products exist" must {
val expectedStatusCode = Status.Ok
s"return $expectedStatusCode and an empty list" in {
def service: HttpRoutes[IO] =
Router("/" -> new ProductsRoutes(emptyRepository).routes)
val response: IO[Response[IO]] = service.orNotFound.run(
Request(method = Method.GET, uri = Uri.uri("/products"))
)
val result = response.unsafeRunSync
result.status must be(expectedStatusCode)
result.as[List[Product]].unsafeRunSync mustEqual List.empty[Product]
}
}
"products exist" must {
val expectedStatusCode = Status.Ok
s"return $expectedStatusCode and a list of products" in {
forAll("products") { ps: List[Product] =>
val repo: Repository[IO] = new TestRepository[IO](ps)
def service: HttpRoutes[IO] =
Router("/" -> new ProductsRoutes(repo).routes)
val response: IO[Response[IO]] = service.orNotFound.run(
Request(method = Method.GET, uri = Uri.uri("/products"))
)
val result = response.unsafeRunSync
result.status must be(expectedStatusCode)
result.as[List[Product]].unsafeRunSync mustEqual ps
}
}
}
}
"POST /products" when {
"request body is invalid" must {
val expectedStatusCode = Status.BadRequest
s"return $expectedStatusCode" in {
def service: HttpRoutes[IO] =
Router("/" -> new ProductsRoutes(emptyRepository).routes)
val payload = scala.util.Random.alphanumeric.take(256).mkString
val response: IO[Response[IO]] = service.orNotFound.run(
Request(method = Method.POST, uri = Uri.uri("/products"))
.withEntity(payload.asJson.noSpaces)
)
val result = response.unsafeRunSync
result.status must be(expectedStatusCode)
result.as[String].unsafeRunSync must be("Invalid value for: body")
//result.body.compile.toVector.unsafeRunSync must be(empty)
}
}