Error occuring in testing my controller with RSPEC using shoulda matchers especially create i can't able to test save functionality

Viewed 28

I am testing my controller with RSPEC using shoulda matchers while i came across the create method in my controller i cant test the save function if i try to do that i go the error

Expected response to be a <3XX: redirect>, but was a <200: OK> i have attached my controller part and testing and route

In testing

 RSpec.describe "routes for home", type: :routing do
   describe 'post #create' do
      before do
        post :create , params: params
      end
    
      context 'when the params are correct' do
        let(:params) { { restaurant: { restaurantname: "Buhari" ,location_id: 1} } }

        it 'is expected save successfully and redirect_to gridpage' do
         expect(assigns[:restaurant].save).to redirect_to(gridurl_path)
        end


    end

 end
end

In controller

  def create
    # render plain: params
    @restaurant=Restaurant.new(restaurant_params)


    if @restaurant.save
        redirect_to gridurl_path
    else
        render 'index'
    end
  end

In routes

  post "/home/create", to: "home#create", as: :createurl
  get '/home/grid', to: 'home#grid',as: :gridurl

Thank you in advance

1 Answers

First I suggest you read https://relishapp.com/rspec/rspec-rails/docs/controller-specs and also the other docs. They will give you a good starting point on how to test stuff with rspec.

When you look at a controller action, you are not interested on who's doing what (i.e assigns[:restaurant]) - you want to see if a redirect happens, if something is saved in the DB, etc. Think of it from the perspective of a user calling that endpoint. Does the user know all of the internals?

Here is how it should look like:

describe "routes for home", type: :controller do
  describe 'post #create' do
    context 'when the params are correct' do
      let(:params) { { restaurant: { restaurantname: "Buhari" ,location_id: 1} } }

      it 'is expected save successfully and redirect_to gridpage' do
        post :create, params: params
        expect(response).to redirect_to('/home/grid')
      end
    end
  end
end
Related