Search code examples
ruby-on-railsrspectddrspec-rails

Rspec request spec ActionController::RoutingError


I'm trying to rewrite my tests in Rspec and am stuck on trying to make an update to a user. I'm sure this is a silly thing I'm overlooking, but I've looked everywhere and can't find an answer.

Here's myspec file:

require 'spec_helper'

describe UsersController, type: [:request, :controller]  do

before(:each) { host! 'localhost:3000/' }

describe "#update" do

it "doesn't update user" do
  form_params = {
    params: {
    id: 1,
    email: "hello@example",
    name: "hello"
    }
  }
  patch :update, params: form_params


    end
  end
end

It seems like the :update portion is wrong but as far as I can see in my routes, there's no other way to call it.

Here's the error:

ActionController::RoutingError: No route matches [PATCH] "/update"

Here's my routes:

       new_user GET    /users/new(.:format)                    users#new
      edit_user GET    /users/:id/edit(.:format)               users#edit
           user GET    /users/:id(.:format)                    users#show
                PATCH  /users/:id(.:format)                    users#update
                PUT    /users/:id(.:format)                    users#update
                DELETE /users/:id(.:format)                    users#destroy

Here's my old test:

  test "should redirect update when not logged in" do
    patch user_path(@user), params: { user: { name: @user.name, email: @user.email } }
    assert_not flash.empty?
    assert_redirected_to login_url
  end

And if you guys possibly know - how do I convert assert_not flash.empty? to Rspec? Thanks so much in advance!


Solution

  • At first, you can't to use multiple types in type: [:request, :controller]. If you want to write request specs you have to specify named route (user_path) or url ("/users/:id")

    require 'spec_helper'
    describe UsersController, type: :request  do
      describe "#update" do
        let(:user) { create :user } # or use fixtures here
    
        # I'm just a bit confused here, why it should not update?
        it "doesn't update user" do
          patch user_path(user), email: "hello@example", name: "hello"
          expect(flash.empty?).to eq false
          expect(response).to redirect_to login_path
        end
      end
    end