ruby-on-railsactiondispatch

ActionController::UrlGenerationError: No route matches and missing id even though I am passing the id to the test


I'm still new to rails and trying to write some basic tests for one of my controllers.

For the sake of keeping this question brief, let's look at two of my tests.

From the error below, I can see the missing required keys: [:id] issue, but I am passing the id in - so I can't figure out what the issue is.

Appreciative of any help :)

The test file (only included the relevant tests to this question)

require 'test_helper'

class CaptablesControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

  setup do
    @captable = captables(:one)
  end

  setup do
    @company = companies(:one) 
  end

  setup do 
    @user = users(:one) 
  end

  test "should show captable" do
    sign_in @user
    get company_captable_url(@captable), id: @captable.id
    assert_response :success
  end

  test "should get index" do
    sign_in @user
    get company_captables_url(@company)
    assert_response :success
  end
....

The controller (just included the relevant methods)

class CaptablesController < ApplicationController
  before_action :set_company
  before_action :set_captable, only: [:show, :edit, :update, :destroy]

  def index
    @captables = @company.captables
  end

  def show
    @captable = Captable.find(params[:id])
  end
.....

The cap tables fixture

one:
  id: 1
  version: 1
  name: MyText
  company_id: 1

This is the error when trying to run the test

Error:
    CaptablesControllerTest#test_should_show_captable:
    ActionController::UrlGenerationError: No route matches {:action=>"show", :company_id=>#<Captable id: 1, version: 1, name: "MyText", company_id: 1, created_at: "2018-10-17 18:34:14", updated_at: "2018-10-17 18:34:14", total_stocks_in_company: nil>, :controller=>"captables"}, missing required keys: [:id]
        test/controllers/captables_controller_test.rb:41:in `block in <class:CaptablesControllerTest>'


    bin/rails test test/controllers/captables_controller_test.rb:39

Solution

  • ActionController::UrlGenerationError: No route matches {:action=>"show", :company_id=>Captable id: 1, version: 1, name: "MyText", company_id: 1, created_at: "2018-10-17 18:34:14", updated_at: "2018-10-17 18:34:14", total_stocks_in_company: nil, :controller=>"captables"}, missing required keys: [:id]

    Your path helper company_captable_url which I believe is constructed with nested resources. So it expects values for two dynamic segments i.e, :company_id and :id. So @company should be passed along with @captable. You need to change it to below

    test "should show captable" do
      sign_in @user
      get company_captable_url(@company, @captable)
      assert_response :success
    end