I’m just getting started with Ember and come across this issue while writing some jasmine tests.
Given I have the following code
App.RecipeController = Ember.Controller.extend
selectedGrain: null
amount: null
recipeGrains: Ember.A()
totalWeight: (->
weight = 0
@get('recipeGrains').forEach (grain) ->
weight += grain.get('weight')
weight
).property('recipeGrains.@each')
addGrain: ->
grain = Ember.Object.create
name: @get('selectedGrain').get('name')
weight: parseFloat(@get('amount'))
@get('recipeGrains').pushObject(grain)
@set('selectedGrain', null)
@set('amount', null)
And I write the following test.
describe("Controllers", function() {
describe("NewRecipeController", function() {
var controller;
beforeEach(function() {
controller = Brewery.NewRecipeController.create();
});
it("calculates the correct total weight", function() {
var grains = controller.get('recipeGrains');
grains.pushObject(Ember.Object.create({weight: 4.0}));
grains.pushObject(Ember.Object.create({weight: 3.2}));
expect(controller.get('totalWeight')).toEqual(7.2);
});
it ("adds grains based on its selected grain", function() {
controller.set('selectedGrain', Ember.Object.create({name: "Wheat"}));
controller.set('amount', '10.2');
controller.addGrain();
expect(controller.get('totalWeight')).toEqual(10.2);
});
});
});
I expected that both tests would pass, but instead the second test fails with the message
Expected 17.4 to equal 10.2.
It seems the state of the first test is spilling over the the second test. Can someone more knowledgeable than I pelase explain how Ember handles controller states and why this happens?
Thank you!
The reason why your test fails is the default value initialization @ line 4.
You should either set the initial value in
initmethod inApp.RecipeControlleror passing the value at instance creation:or
You should have a look to section 6 of this article.