Search code examples
ruby-on-railsrubyunit-testingjrubyruby-test

ActionController::RoutingError: No route matches error while unit testing


I found a lot of questions with same title but could not found the appropriate answer.

I am testing a controller

Player Controller

def create
 player = Player.create(params[':player'])

if player.valid?
  # if creation successful, log the player in:
  player_session = PlayerSession.create(
    player: player,
    session_token: ActiveSupport::SecureRandom.urlsafe_base64
  )

  render json: {session_token: player_session.session_token}
else
  render json: {error: "Player name already exists."}, status: :unprocessable_entity
 end
end

Player Controller Test

test "create" do
    post(:create,
            {
                'player' => {
                    'player_name' => "usman", 
                    'password' => 123, 
                    'email' => '[email protected]'
                }
            }
        )
    assert_select response.body
end

while executing the test file the following errors display on console.

ActionController::RoutingError: No route matches {:player=>{"player_name"=>"usman", "password"=>123, "email"=>"[email protected]"}, :controller=>"pl
ayers", :action=>"create"}
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_dispatch/routing/route_set.rb:424:in `raise_routing_error'
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_dispatch/routing/route_set.rb:406:in `generate'
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_dispatch/routing/route_set.rb:453:in `generate'
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_dispatch/routing/route_set.rb:449:in `generate_extras'
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_dispatch/routing/route_set.rb:445:in `extra_keys'
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_controller/test_case.rb:143:in `assign_parameters'
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_controller/test_case.rb:402:in `process'
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_controller/test_case.rb:47:in `process'
    D:/jruby-1.7.1/lib/ruby/gems/shared/gems/actionpack-3.0.3/lib/action_controller/test_case.rb:355:in `post'
    D:/Projects/lyricle/test/functional/players_controller_test.rb:5:in `test_create'
    org/jruby/RubyBasicObject.java:1659:in `__send__'

why this error is here?


Solution

  • You have to define routes if you want anything to be able to access your controller.

    So, in your config/routes.rb :

    App::Application.routes.draw do
      resources :your_resource_plural_name
    end