How to use fixtures or pretender in an Integration test


(Robin Ward) #1

Discourse has a bunch of integration tests in the Javascript suite. The Ember API for this is really cool. You can do something like:

integration("View Topic");

test("Enter a Topic", function() {
  expect(2);

  visit("/t/internationalization-localization/280");
  andThen(function() {
    ok(exists("#topic"), "The was rendered");
    ok(exists("#topic .post-cloak"), "The topic has cloaked posts");
  });
});

You might wonder how the Javascript suite gets the data that it wants to render that test. There are two ways you can do this, both are not very hard!

The First Way: JSON Fixtures

In the test environment, any requests for a path such as /search will look for a fixture with that name rather than performing the AJAX request.

The fixtures are defined in the fixtures folder. Each file in there simply exports a Javascript object where they key is the path and the value is the JSON response.

To generate a fixture, I recommend doing an anonymous GET on meta.discourse.org and using the reply there. I know this isn’t ideal and in the future I want to make generating fixtures easier, but for now it works well enough to write tests.

The Second Way: Pretender

We use Pretender to mock a server. The code for the mock server is in in create-pretender.js.

Pretender is an awesome alternative to using fixtures for entire responses, and it has the benefit that you can use it to conditionally return different responses, say for a test that checks that logging in works.

I like Pretender so much I even made a screencast on it. It’s setup slightly differently in Discourse but it shouldn’t be hard to follow!


How are routes in acceptance tests declared?