Nested describes

Nested describes are useful when you want to describe similar behavior between specs. Suppose we want the following two new acceptance criteria:

  • Given an investment, when its stock share price valorizes, it should have a positive return of investment (ROI);
  • Given an investment, when its stock share price valorizes, it should be a good investment.

They both share the same behavior when its stock share prices valorizes.

To translate this into Jasmine you can nest a call to the describe function inside the existing one in the spec/InvestmentSpec.js file: (I removed the rest of the code for the purpose of demonstration; it is still there.)

describe("Investment", function()
  describe("when its stock share price valorizes", function() {
   
  });
});

It should behave just like the outer one, so you can add specs (it) and use setup and teardown functions (beforeEach, afterEach).

Setup and teardown

When using setup and teardown functions, Jasmine respects the outer setup and teardown functions as well, so they are run as expected. For each spec (it):

  • Jasmine runs all setup functions (beforeEach) from the outside in
  • Runs a spec code (it)
  • Runs all the teardown functions (afterEach) from the inside out

So we can add a setup function to this new describe that changes the share price of the stock, so it's greater than the share price of the investment:

describe("Investment", function() {
  var stock;
  var investment;

  beforeEach(function() {
    stock = new Stock();
    investment = new Investment({
      stock: stock,
      shares: 100,
      sharePrice: 20
    });
  });

  describe("when its stock share price valorizes", function() {
    beforeEach(function() {
      stock.sharePrice = 40;
    });
  });
});

Coding a spec with shared behavior

Now that we have the shared behavior implemented, we can start coding the acceptance criteria described earlier. Each is, just as before, a call to the global Jasmine function it:

describe("Investment", function() {
  describe("when its stock share price valorizes", function() {
    beforeEach(function() {
      stock.sharePrice = 40;
    });

    it("should have a positive return of investment", function() {
      expect(investment.roi()).toEqual(1);
    });

    it("should be a good investment", function() {
      expect(investment.isGood()).toBeTruthy();
    });
  });
});

And after adding the missing functions to Investment in src/Investment.js:

Investment.prototype.roi = function() {
  return (this.stock.sharePrice - this.sharePrice) / this.sharePrice;
};

Investment.prototype.isGood = function() {
  return this.roi() > 0;
};

You can run the specs, and see that they are passing:

Coding a spec with shared behavior

Passing nested describe specs

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.233