测试:没有路由匹配{:action =>“show”,:controller =>“users”,:id => nil}

时间:2012-07-25 14:13:23

标签: ruby-on-rails testing rspec routes

我只有2周时间在铁轨上学习红宝石和红宝石。 目前我的问题是te路线匹配我不太了解,现在我正在测试rspec这个:

require 'spec_helper'

describe UsersController do

it "should redirect to the user show page" do
post :create, :users => @attr
response.should redirect_to(user_path(assigns(:users)))
end
  describe "signup" do

before { visit new_user_registration_path }

let(:submit) { "Sign up" }

describe "with invalid information" do
  it "should not create a user" do
    expect { click_button submit }.not_to change(User, :count)
  end
end

describe "with valid information" do
  before do
    fill_in "Email", :with=> "user@example.com"
    fill_in "Password", :with=> "foobar"
    #fill_in "password_confirmation", :with=> "foobar"
  end

  it "should create a user" do
    expect { click_button submit }.to change(User, :count).by(1)
  end
end
end
end 

我在我的UserController上有这个

class UsersController < ApplicationController

def new
     @user = User.new
end

def create
    @user = User.new(params[:user])
    if @user.save
        redirect_to user_session_path
    else
    redirect_to new_user_session_path
end

end

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

但是当我运行测试时出现了这个错误:

Failures:

1) UsersController should redirect to the user show page
   Failure/Error: response.should redirect_to(user_path(assigns(:users)))
   ActionController::RoutingError:
   No route matches {:action=>"show", :controller=>"users", :id=>nil}
   # ./spec/controllers/user_controller_spec.rb:7

2) UsersController signup with valid information should create a user
   Failure/Error: expect { click_button submit }.to change(User, :count).by(1)
   count should have been changed by 1, but was changed by 0
   # ./spec/controllers/user_controller_spec.rb:29

1 个答案:

答案 0 :(得分:2)

在您的规范中,您指的是两次用户(复数)而不是用户(单数):

it "should redirect to the user show page" do
  post :create, :user => @attr
  response.should redirect_to(user_path(assigns(:user)))
end

应该通过。

<强>更新

如果未设置@attr,您当然应该正确设置它。只需提供包含模型的所有属性和值的哈希值。假设用户模型具有属性名称和地址:

@attr = { :name => "SomeUserName", :address => "SomeAddress"}