Unit Testing multiple controllers in emberjs


#1

I’ve included an example below of testing controllers that depend on other controllers (through the needs) and how to create those controllers. There might be a better way, if so, feel free to inform me, I was just happy to get it working.

describe("Application.bookController", function () {
  var bookController, bookModel, userController, userModel;

  beforeEach(function () {
    Application.reset();
    Ember.run(function () {
      userModel = Application.User.create(Application.UserFixtures[0]);
      bookModel = Application.book.create(Application.bookFixtures[0]);
      // if you manualy are creating a controller that depends on another, you need to cheat
      var container = Application.__container__;
      userController = container.lookup('controller:user');
      userController.set('model', userModel);

      bookController = container.lookup('controller:book');
      bookController.set('model', bookModel);
    });
  });

  it("should have a computed property isMyBook that returns true if is_my_book equals true and the user_id matches the owner book_owner_user_id in the returned JSON", function () {
    Ember.run(function () {
      // isMyBook compares the current users user_id to the book owner's user id (hence the need to hit the users controller from the book) - note this is a made up example
      expect(bookController.get('isMyBook')).toBeTruthy();
    });
  });

  afterEach(function () {
    Ember.run(function () {
      bookModel.destroy();
      bookController.destroy();

      userModel.destroy();
      userController.destroy();
    });
  });

});