1

在我的 rails 应用程序中,我使用 devise 来验证用户身份。我需要为属于用户的控制器艺术创建 rspec 测试。

我的艺术模型如下:

class Art < ActiveRecord::Base
  belongs_to :user
  attr_accessible :description, :title, :image
  has_attached_file :image, :styles => { :medium => "620x620>", :thumb => "200x200>" }

  validates :title,       :presence => true
  validates :description, :presence => true
  validates :image,       :presence => true
end

在我的 ArtsController 中,我有以下代码:

class ArtsController < ApplicationController
  before_filter :authenticate_user!

  def create
    @user = current_user
    @art = @user.arts.create(params[:art])
  end
end

我正在尝试创建一个测试,以检查用户在尝试创建艺术但未登录时是否被重定向到登录页面。所以我的测试如下所示:

describe ArtsController do
  describe "When user is not logged in" do
    it "should be redirected to sign in page if creating new art" do
      post :create
      response.should redirect_to '/users/sign_in'
    end
  end    
end

但我收到以下错误:

  1) ArtsController When user is not logged in should be redirected to sign in page if creating new art
     Failure/Error: post :create
     ActionController::RoutingError:
       No route matches {:controller=>"arts", :action=>"create"}
     # ./spec/controllers/arts_controller_spec.rb:11:in `block (3 levels) in <top (required)>'

我的 routes.rb 是这样的:

Capuccino::Application.routes.draw do
  devise_for :users
  match "home" => "users#home", :as => :user_home
  resources :users do
    resources :arts
  end
  match "home/art/:id" => "arts#show", :as => :art
  match "home/arts" => "arts#index", :as => :arts
end

我的 rspec 测试应该如何执行此测试?

4

1 回答 1

0

您没有任何路由arts#create,只会将控制器和操作作为参数。

如果您想使用当前的嵌套路由,则必须在请求中传递:user_id参数:

it "should be redirected to sign in page if creating new art" do
  post :create, { :user_id => user_id }
  response.should redirect_to '/users/sign_in'
end

但是由于您正在尝试测试没有 的用例,因此:user_id需要一个新的非嵌套路由。

于 2013-10-02T03:05:32.710 回答