jeudi 21 avril 2016

Explanation of why "Expected result to have changed by 1 but was changed by 0" error happens and what to do to fix it

I have a feature in which a user is able to add a new location, and i'm having a hard time adding a test to it. (I'm horrible at testing, trying very hard to get better.)

I feel like I am very close to getting this test to work. The only error that I am running into right now is

expected result to have changed by 1, but was changed by 0

Now I don't know what i'm doing wrong. I'm wondering if someone could help me with what would allow this test to pass, but also kind of an explanation of what is happening when this error happens. I'm really trying to become better a testing as its been something i've avoided and until recently accepted the importance of it, and had the courage to understand it.

Here is my spec file

require 'spec_helper'

describe Admin::LocationsController, type: :controller do
  let(:admin) { FactoryGirl.create(:admin) }

  context 'super admin' do
    let!(:super_admin) { FactoryGirl.create(:super_admin) }

  before(:each) do
    sign_in(:user, super_admin)
  end

  describe '#create' do
    it 'creates a new location' do

      expect{
        post :create, location: {
          name: 'sample location',
          phone: '5555555555',
          fax: '5555555555',
          location_id: '123456',

          address_attributes: {
            address1: '12345 Some St',
            city: 'Portland',
            state: 'OR',
            zip: '91237'
          }
        }, format: :json

      }.to change {Location.count}.by(1)

      new_location = Location.last
      expect(new_location.name).to eq 'sample location'
      expect(new_location.phone).to eq '5555555555'
      expect(new_location.fax).to eq '5555555555'
      expect(new_location.location_id). to eq '123456'
      expect(new_location.address.address1).to eq '12345 Some St'
      expect(new_location.address.city).to eq 'Portland'
      expect(new_location.address.state).to eq 'OR'
      expect(new_location.address.zip).to eq '91237'
    end
  end
end

And here is my factory

FactoryGirl.define do
  factory :location do |c|
    c.name 'sample location'
    c.phone '5555555555'
    c.fax '5555555555'
    location_id '123456'
    association :address, factory: :address
  end
end

Aucun commentaire:

Enregistrer un commentaire