Getting a "Expected response to be a <:redirect>, but was <200>" when trying to pass a test

StackOverflow https://stackoverflow.com/questions/19746045

  •  03-07-2022
  •  | 
  •  

Pregunta

Just to clarify: I'm new to Ruby and Rails.

I've tryed to solve my problem with the sugestions in here, here and here, but they didn't seem to have direct relation with my problem, or I'm too dumb do understand.

I'm trying to test a scenario where I don't update an object and I want my app to redirect. I'm not sure if my controller code is right, I think I'm probably not covering this scenario. Here's my test code:

  test "should not update status if nothing has changed" do
    sign_in users(:rodrigo)
    put :update, id: @status
    assert_redirected_to status_path(assigns(:status))
    assert_equal assigns(:status).user_id, users(:rodrigo).id
  end

, and my controller update code:

  def update
    @status = current_user.statuses.find(params[:id])
    @document = @status.document
    if params[:status] && params[:status].has_key?(:user_id)
      params[:status].delete(:user_id)
    end
    respond_to do |format|
      if @status.update_attributes(params[:status]) &&
         @document && @document.update_attributes(params[:status][:document_attributes])
        format.html { redirect_to @status, notice: 'Status was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @status.errors, status: :unprocessable_entity }
      end
    end
  end

I've already tried to verify if @status.changed?, and it really didn't. I'm without options here. If anyone want to help and need more information, I can provide it.

¿Fue útil?

Solución

Facepalm for me...

I've mentioned in my question:

I've already tried to verify if @status.changed?, and it really didn't.

It did change when I put something different in one of the model attributes, but I've only asked .changed? after saving my @status model. I'm really sorry about it, I'm yet just figuring out how Ruby on Rais works.

That said, I've came up with a solution to my problem, that was just setting the only one attribute of my model (except the id, of course) with the value from the params[:status] hash. And BEFORE saving it, I ask if @status.changed?. If it doesn't, I redirect_to the unchanged @status, otherwise, I just save it and go through the old code.

Of course that doesn't cover all my scenario, since I also have to check if my @document model has changed, but this is not the scope of this question.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top