我正在尝试使用名称空间测试控制器,以下是我的控制器(/admin/sites_controller.rb):
class Admin::SitesController < AdminController
def create
@site = Site.new(params[:site])
respond_to do |format|
if @site.save
format.html { redirect_to(@site, :notice => 'Site was successfully created.') }
format.xml { render :xml => @site, :status => :created, :location => @site }
else
format.html { render :action => "new" }
format.xml { render :xml => @site.errors, :status => :unprocessable_entity }
end
end
end
end
以下是我的routes.rb
文件
namespace :admin do
resources :sites
end
我正在使用rspec2来测试我的控制器,以下是我的控制器规范
describe Admin::SitesController do
describe "POST create" do
describe "with valid params" do
it "creates a new Site" do
expect {
post :create, :site => valid_attributes
}.to change(Site, :count).by(1)
end
end
end
end
但是当我运行规范时,它会给我以下路由错误
Admin::SitesController POST create with valid params creates a new Site
Failure/Error: post :create, :site => valid_attributes
NoMethodError:
undefined method `site_url' for #<Admin::SitesController:0xb5fbe6d0>
# ./app/controllers/admin/sites_controller.rb:47:in `create'
# ./app/controllers/admin/sites_controller.rb:45:in `create'
# ./spec/controllers/admin/sites_controller_spec.rb:78
# ./spec/controllers/admin/sites_controller_spec.rb:77
我想这是因为我正在使用'admin'名称空间,但我该如何解决?
我正在使用
答案 0 :(得分:1)
当您为路由命名空间时,您将创建如下所示的URL和路径助手:
HTTP Verb Path action helper
GET /admin/sites index admin_sites_path
GET /admin/sites/new new new_admin_site_path
POST /admin/sites create admin_sites_path
GET /admin/sites/:id show admin_site_path(:id)
GET /admin/sites/:id/edit edit edit_admin_site_path(:id)
PUT /admin/sites/:id update admin_site_path(:id)
DELETE /admin/sites/:id destroy admin_site_path(:id)
因此,您可以直接在代码中使用它们(例如redirect_to admin_site_path(@site)
),也可以执行以下操作:
redirect_to([:admin, @site])