Nested describes are useful when you want to describe similar behavior between specs. Suppose we want the following two new acceptance criteria:
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
).
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
):
beforeEach
) from the outside init
)afterEach
) from the inside outSo 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; }); }); });
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: