没有路线匹配{:action =>“show”,:controller =>“user”,:id => nil}

时间:2012-07-18 15:34:46

标签: ruby-on-rails testing rspec routes

各位大家好,我有这个问题(帖子标题)。

Failure/Error: get :create, :user => { :email => 'foo@example.com', :name => 'userexample' }
ActionController::RoutingError:No route matches {:action=>"show", :controller=>"user", :id=>nil}

这是我的UserController

class UserController < ApplicationController

  def new
  end

  def create
    @user = User.new(params[:user])
    @user.save
    redirect_to :action => :show, :id => @user.id
  end

  def show
    @user = User.find(params[:id])
  end
end

这是我的routes.rb

::Application.routes.draw do

  devise_for :users
  root :to => "user#index"
  resources :user
  #match "newuser" => "user#new"
  get "user/new"
  post "user/create"
  get "user/:id" => "user#show"

这是我的rspec测试

require 'spec/spec_helper'

describe UserController do
  it "create new user" do
    get :create, :user => { :email => 'foo@example.com', :name => 'userexample' }
      flash[:notice] = 'new user was successfully created.'
    end
  end
end

2 个答案:

答案 0 :(得分:5)

if @user.save
   redirect_to :action => :show, :id => @user.id
else
 ...
end

答案 1 :(得分:1)

大多数Rails应用程序使用此类型的内容块来创建和更新记录。

def create
  @user = User.new(params[:user])

  if @user.save
    redirect_to @user, :notice => "User was created successfully."
  else
    render :new
  end
end

基本上,当create操作运行时,它会创建新记录或User模型的新实例。

当调用.save时,它会检查所有验证。如果验证通过则返回true,否则返回false。

如果返回false,则需要再次呈现:new模板,以便人员有机会修复任何验证错误。

如果返回true,则您希望重定向到show操作。关于rails的酷炫之处在于it can automatically figure that out只需传递实例@user


Ryan Bates有testing controllers with RSpec的教程。根据他的所作所为,这就是我测试你的控制器的方式。

require 'spec/spec_helper'

describe UserController do

  describe "POST 'create'" do

    it "should redirect to user on successful save" do
      User.any_instance.stub(:valid?) { true }
      post :user
      flash[:notice].should_not be_nil
      assigns(:user).should_not be_a_new_record
      response.should redirect_to(assigns(:user))
    end

    it "should render new template on failed save" do
      User.any_instance.stub(:valid?) { false }
      post :user
      flash[:notice].should be_nil
      assigns(:user).should be_a_new_record
      response.should render_template(:new)
    end

    it "should pass params" do
      User.any_instance.stub(:valid?) { true }
      post :user, :user => { email_address: "baylor@example.com" }
      assigns(:user).email_address.should == "baylor@example.com"
    end
  end
end