Creating fixtures for Unit Tests

In many of our gems, we have a need for Unit fixtures (parsing specifically). So, to make this easier, we have created some tools to help.

Method 1: using bin/create_fixture

If the required page does not require any specific Javascript functionality, meaning the page returned is the one we are processing, then we can use the bin/create_fixture that has been added to most gems in the bin folder. This tool uses CURL which much be present on the host machine to download the HTML file, and store it in the fixture/webmock folder.

To use it, issue the command bin/create_fixture with the argments:

bin/create_fixture https://audienti.com/ audienti.mock

wherehttps://audienti.com/ is the URL you want to retrieve, and audienti.mock is in the name of the file stored in the fixture/webmock folder.

Method 2: Using Splash Server

In cases where the page has Javascript that renders, and this rendering is what causes the final page to be delivered, you will need to use the Splash servers to retrieve the raw HTML and generate the mock file yourself.

To do this, login to the web UI for Splash. You will need the username and password. From there, you place the URL you want to retrieve in the URL box, modify the script to the one that is listed below by cutting and pasting, and then hit the retrieve button.

Once you do this, you'll have the option to download the HTML. Do this, paste the HTML page into a file in the appropriate fixture folder, with the correct name. Then, IF the fixture requires stubbing to a request, add to the top of this page the following code snippet to set the HTML retriever part of the fixture.

This will setup the mock just like the bin/create_fixture does.

File format

If you look at this file, it will have two primary "parts". The first part is the HTTP response codes, and headers that are returned. After this part, you will have the HTML returned. The beginning of a mock looks like this:

Stubbing/mocking in RSpec

From there, you will need to stub/mock in RSpec. The primary way this happens, is via the stub with mock method that is defined in the support folder. This method takes a matcher as a regular expression, a filename (from the fixture folder as the root), and a method to match which defaults to :any, and will return this document and response code of this file.

Using the stubber is easy, you simply do the following:

Last updated