在我的rails应用程序中,我使用devise来验证用户身份。我需要为属于用户的控制器Arts创建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
我正在尝试创建一个测试来检查用户是否在尝试创建艺术作品时重定向到登录页面但未登录。所以我的测试如下所示:< / p>
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测试应该如何进行此测试?
答案 0 :(得分: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
的用例,那么您需要一个新的非嵌套路由。