jeudi 27 avril 2017

Controller test for nested resources

can't go over the problem with CREATING INDEX ROUTE TEST for nested attribute. I've been trying all my ideas but nothing works

I have Service model and ServiceRoute model.

ServiceRoute belongs_to Service

and

Service has_many ServiceRoutes.

Here is my controller:

class ServiceRoutesController < ApplicationController

before_action :set_service_route, only: [:show, :update, :destroy]
before_action :set_service, only: :create


def create
  @service_route = @service.service_routes.build(service_route_params)

  if @service_route.save
    render json: @service_route, status: :created, location: @service_route
  else
    render json: @service_route.errors, status: :unprocessable_entity
  end
end


private

  def set_service_route
    @service_route = ServiceRoute.find(params[:id])
  end

  def set_service
   @service = Service.find(params[:service_id])
  end

  def service_route_params
    params.require(:service_route).permit(:routes_list, :service_id)
  end
end

I create ServiceRoute with build method

My routes.rb file:

resources :services do
  resources :service_routes
end

Test "should create service route" has an error:

ActionController::UrlGenerationError: No route matches {:action=>"index", :controller=>"service_routes"} missing required keys: [:service_id]

test "should create service_route" do
 assert_difference('ServiceRoute.count') do
  post service_service_routes_url, params: { service_route: {routes_list: 
  @service_route.routes_list, service_id: @service_route.service_id } }, 
 as: :json
end

How should I refactor this test to match the route: /services/:service_id/service_routes

Aucun commentaire:

Enregistrer un commentaire