【问题标题】:Rails3 and Rspec2 controller testing with a namespace使用命名空间进行 Rails3 和 Rspec2 控制器测试
【发布时间】:2011-12-01 19:12:52
【问题描述】:

我正在尝试使用名称空间测试控制器,以下是我的控制器 (/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

我猜是因为我使用了“管理员”命名空间,但我该如何解决呢?

我正在使用

  • Rails3
  • Rspec2
  • Linux

【问题讨论】:

  • 嗨 iWasRobbed,对不起,我会继续努力的,谢谢

标签: ruby-on-rails-3 controller integration-testing rspec2


【解决方案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])

【讨论】:

  • 嗨@iWasRobbed,谢谢你是对的,这是控制器端的问题(重定向问题)
猜你喜欢
  • 2011-07-16
  • 2023-03-16
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多