0

The following method passes tests appropriately:

def associate_grid_location
        devices.each do |device|
            if device.grid_location and grid_location_id.nil?
                update_attribute(:grid_location_name,device.grid_location.grid_name)
                update_attribute(:grid_location_id,device.grid_location_id)
                break
            end
        end
    end

However if I run the same test logic on a call to this method, it fails to update each cabinets' grid_location_name and grid_location_id:

def self.associate_grid_locations
        Cabinet.all.each do |cabinet|
            cabinet.associate_grid_location
        end
    end

Please suggest why it may be failing.

Passing test:

test "Cabinet associate grid location from device where device has grid location" do
    @cabinet = cabinets(:one)
    @cabinet.grid_location_id = nil
    @device = devices(:one)
    @grid_location = grid_locations(:one)
    @grid_location.grid_name = "test location"
    @device.grid_location = @grid_location
    @cabinet.devices << @device
    @cabinet.associate_grid_location

    assert_equal @grid_location.grid_name, @cabinet.grid_location_name, "Failed: Did not update cabinet grid location"
    assert_equal @device.grid_location.id, @cabinet.grid_location_id, "Failed: Did not update cabinet grid location"
  end

Failing test:

test "Cabinet associate grid location from device where device has grid location (Called on Cabinet)" do
    @cabinet = cabinets(:one)
    @cabinet.grid_location_id = nil
    @device = devices(:one)
    @grid_location = grid_locations(:one)
    @grid_location.grid_name = "test location"
    @device.grid_location = @grid_location
    @cabinet.devices << @device
    Cabinet.associate_grid_locations

    assert_equal @grid_location.grid_name, @cabinet.grid_location_name, "Failed: Did not update cabinet grid location"
    assert_equal @device.grid_location.id, @cabinet.grid_location_id, "Failed: Did not update cabinet grid location"
  end

Thank you.

Joe Essey
  • 3,457
  • 8
  • 40
  • 69

1 Answers1

0

Cabinet.associate_grid_locations calls Cabinet.all, which instantiates new objects (unless you have identity-map enabled) that are not linked to the objects you have instantiated in your test. Calling #reload on @cabinet should make the test pass, assuming there are no other errors.

Brian Hahn
  • 438
  • 5
  • 5
  • Can you please explain a bit further? Where do I call reload? Right before the call to `Cabinet.associate_grid_locations `? – Joe Essey May 14 '13 at 14:49
  • The call to `Cabinet.associate_grid_locations` updates the database, so you'd want to call reload **after** that call such that the object in your test is populated with the updated data. – Brian Hahn May 14 '13 at 19:50