0

我发现了很多标题相同的问题,但找不到合适的答案。

我正在测试控制器

播放器控制器

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

播放器控制器测试

test "create" do
    post(:create,
            {
                'player' => {
                    'player_name' => "usman", 
                    'password' => 123, 
                    'email' => 'ranasaani@gmail.com'
                }
            }
        )
    assert_select response.body
end

在执行测试文件时,控制台上会显示以下错误。

ActionController::RoutingError: No route matches {:player=>{"player_name"=>"usman", "password"=>123, "email"=>"ranasaani@gmail.com"}, :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__'

为什么这个错误在这里?

4

2 回答 2

1

如果您希望任何东西能够访问您的控制器,则必须定义路由。

所以,在你的config/routes.rb

App::Application.routes.draw do
  resources :your_resource_plural_name
end
于 2013-09-13T11:01:28.087 回答
1

创建动作应该是这样的:

def create
 @player = Player.new(params[:player])
 #your code
end

您还需要在创建操作之前添加新操作:

 def new
    @player = Player.new
end

在 routes.rb 你应该有resources :players

@player是一个实例变量,使您也可以在视图中调用它。

请参阅Rails 指南以创建您的第一个应用程序。

还要检查Rails for Zombies,它们非常好

于 2013-09-13T11:03:21.737 回答