mardi 13 septembre 2016

Rails testing: how to pass a hash to a controller

Alright, the title is probably not 100% fitting but i simply don't know hot to better phrase it. Here is my problem: This is my controller: (clip_controller.rb)

def create
    if album_to_display.nil?
        @clip=current_user.clips.build(clip_params)
    else
        @clip=Album.find(album_to_display).clips.build(album_params)
    end
    if @clip.save
        flash[:success]="Clip added!"
        if album_to_display.nil?
            redirect_to clips_user_path(current_user)
        else
            redirect_to albums_user_path(current_user)
        end
    else
        render 'new'
    end
end

and the helpers: (sessions_helper.rb)

def get_album(id)
    session[:album]=id
end

def album_to_display
    @album=session[:album]
end

def album_end_display
    session.delete(:album)
    @album=nil
end

Works all fine. Now I wanted to write a test for it: (clip_create_test.rb)

test "valid creations" do
  ...
  get new_clip_path
  assert_difference "Clip.count", 1 do
    get_album(@album.id)
    post clips_path, params: { clip: { adress: "http://ift.tt/2cSINss",
                                     description: "bum bum bum" } }
  end
  assert_match @album.clips.count, 2
  assert_redirected_to albums_user_path(@user)
end

which fails because @album.clips.count=1. Since Clip.count went up by 1, I assume it must be because album_to_display was nil in the controller. I thought I can avoid that by simply including the SessionsHelper into the test_helper.rb but that does not change anything.

Aucun commentaire:

Enregistrer un commentaire