Rails - 没有路由匹配[POST]

时间:2013-09-06 13:24:35

标签: ruby-on-rails ruby forms testing rspec

为什么我的测试:

feature "Manage todos" do
  scenario "create a new todo" do
    visit root_path
    fill_in 'Email address', with: 'junk@snap2web.com'
    click_button 'Sign in'
    click_link('Add a new todo')
    fill_in 'Description', with: 'Buy some milk'
    click_button 'Create todo'
    expect(page).to have_css 'li.todo', text: 'Buy some Milk'
  end
end

错误:

1) Manage todos create a new todo
  Failure/Error: click_button 'Create todo'
  ActionController::RoutingError:
    No route matches [POST] "/todos/new"

当我的路线有:

Todos::Application.routes.draw do
  root 'high_voltage/pages#show', id: 'homepage'
  resource :session, only: [:create]
  resources :todos
end

和rake路线显示:

   Prefix Verb   URI Pattern               Controller#Action
     root GET    /                         high_voltage/pages#show {:id=>"homepage"}
  session POST   /session(.:format)        sessions#create
    todos GET    /todos(.:format)          todos#index
          POST   /todos(.:format)          todos#create
 new_todo GET    /todos/new(.:format)      todos#new
edit_todo GET    /todos/:id/edit(.:format) todos#edit
     todo GET    /todos/:id(.:format)      todos#show
          PATCH  /todos/:id(.:format)      todos#update
          PUT    /todos/:id(.:format)      todos#update
          DELETE /todos/:id(.:format)      todos#destroy
     page GET    /pages/*id                high_voltage/pages#show

我的控制器有:

$ cat app/controllers/todos_controller.rb 
class TodosController < ApplicationController
  def index
  end

  def new
  end

end

,表格有:

$ cat app/views/todos/new.html.erb 
Add a new todo
<%= form_for :todo do |f| %>
  <%= f.label :description %>
  <%= f.text_field :description %>
  <%= f.submit 'Create todo' %>
<% end %>

4 个答案:

答案 0 :(得分:1)

你应该

<%= form_for Todo.new do |f| %>
在您的视图中

答案 1 :(得分:1)

看看你的路线。正如测试所示,没有路由到todos / new的POST。您需要POST到todos /并在控制器的创建操作中处理它。

答案 2 :(得分:0)

检查您是否在表单中无意中添加了2个表单标记。我这样做是通过复制像这样的bootstrap片段...

<div class="col-sm-8 contact-form">
  <form id="contact" method="post" class="form" role="form">
    <div class="row">

并将其包装在form_for标签中......

<%= form_for @contact, url: contacts_path do |f| %>

令人讨厌的是,它工作正常如果我手动点击按钮但测试失败

答案 3 :(得分:0)

在表单字段中添加路径将重定向到发布路径

<%= form_for :todo do, url: todos_path  |f| %>