   beforeEach module 'app'
 
   beforeEach inject ($rootScope, $controller, _$httpBackend_, authService) ->
-    @scope = $rootScope.$new()
+    loadJSONFixtures 'user.json'
+    @user         = getJSONFixture 'user.json'
+    @scope        = $rootScope.$new()
+    @urlBase      = 'http://api.droneshare.com/api/v1'
+    @authService  = authService
+    @httpBackend  = _$httpBackend_
 
-    loadJSONFixtures 'user.json'
-    @user = getJSONFixture 'user.json'
+  describe 'initialize', ->
+    beforeEach ->
+      @httpBackend.whenGET("#{@urlBase}/auth/user").respond @user
 
-    @urlBase = 'http://api.droneshare.com/api/v1'
+    it 'user is logged out on initialize',  ->
+      expect(@authService.user.loggedIn).not.toBeTruthy()
 
-    @authService = authService
+      @scope.$apply()
+      @httpBackend.flush()
 
-    @httpBackend = _$httpBackend_
-    @httpBackend.expectGET("#{@urlBase}/auth/user").respond @user
+      expect(@authService.user.loggedIn).toBeTruthy()
 
-  it 'user is logged out on initialize',  ->
-    expect(@authService.user.loggedIn).not.toBeTruthy()
+    it 'checks if a user is currently logged in', ->
+      spyOn(@authService, 'setLoggedIn')
 
-    @scope.$apply()
-    @httpBackend.flush()
+      @scope.$apply()
+      @httpBackend.flush()
 
-    expect(@authService.user.loggedIn).toBeTruthy()
-
-  it 'checks if a user is currently logged in', ->
-    spyOn(@authService, 'setLoggedIn')
-
-    @scope.$apply()
-    @httpBackend.flush()
-
-    expect(@authService.setLoggedIn).toHaveBeenCalledWith @user
+      expect(@authService.setLoggedIn).toHaveBeenCalledWith @user
 
   describe 'logout', ->
     beforeEach ->
+      @httpBackend.whenGET("#{@urlBase}/auth/user").respond @user
       @scope.$apply()
       @httpBackend.flush()
 

      expect(@authService.setLoggedIn).toHaveBeenCalled()

  describe 'login', ->
    it 'posts user credentials to API', ->
      @httpBackend.expectPOST("#{@urlBase}/auth/login?login=mrpollo&password=password").respond @user



  describe 'create', ->
    it 'should post payload to API /create', ->
      @httpBackend.whenGET("#{@urlBase}/auth/user").respond @user
      spyOn(@authService, 'postId').and.callThrough()
      payload = jasmine.createSpy('payload')
      @authService.create(payload)
      expect(@authService.postId).toHaveBeenCalledWith 'create', payload

    it 'should login user upon creation', ->
      @httpBackend.whenGET("#{@urlBase}/auth/user").respond 401, {}
      @httpBackend.expectPOST("#{@urlBase}/auth/create").respond @user

      spyOn(@authService, 'setLoggedIn')
