malexanders
malexanders

Reputation: 3343

Rspec/Rails4, object attribute updates not persisting in controller spec?

My controller action does what I want it to in the development environment, and when I follow the process through in the test environment using byebug - the action does what I want, but the attributes I am updating, via update_column in the controller action - is not persisting when I return to my spec. Please see what I have tried below for context.

Controller Action: As I stated above, this action does in fact update the event columns as expected.

def swap
    # TODO
    # Maybe change :event_ids to 'swap_event_ids?'
    if params[:event_ids]
        @swapped_events = params[:event_ids].map{|id| Event.find(id.to_i)}
        byebug
        @swapped_events.each do |event|
            event.update_columns(driver_id: nil)
            event.update_columns(swap_requester_id: current_user.id)
            event.save
        end
        byebug

        flash[:notice] = "Successfully added #{@swapped_events.length} events to swap stack"
        redirect_to(:back)
    else

        flash[:alert] = "Please select one of your events before clicking Swap!"
        redirect_to(:back)
    end
end

The Spec: after returning to the spec, after the post request, the updated columns have not persisted. I.E, the event.driver_id columns are still set to subject.current_user.id.

describe 'POST #swap' do
    login_user

    before do
        request.env['HTTP_REFERER'] = 'http://localhost:3000'
    end

    it '#swap changes driver_id to nil for selected swap request events' do
        events = FactoryGirl.create_list(:event, 2, driver_id: subject.current_user.id)
        post :swap, event_ids: ["#{events[0].id}", "#{events[1].id}"]
        expect(events.all?{|event| event.driver == nil}).to eq true
    end

end

I'm not sure what I am missing here..

Upvotes: 2

Views: 492

Answers (1)

jibiel
jibiel

Reputation: 8303

You need to reload records from the database if you wanna check on the changes:

events.map(&:reload)

Although for the simplicity's sake I'd go with something like:

expect(Event.where(driver_id: nil).count).to eq 2

Upvotes: 3

Related Questions