sameera207
sameera207

Reputation: 16629

Rails3 and Rspec2 controller testing with a namespace

I'm trying to test a controller with a name space, following is my controller (/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

and following is my routes.rb file

namespace :admin do
    resources :sites
end

I'm using rspec2 to test my controller and following is my controller spec

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

But when I run the spec it gives me the following routing error

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

I guess its because of the 'admin' name space I'm using, but how can I fix that?

I'm using

Upvotes: 1

Views: 459

Answers (1)

iwasrobbed
iwasrobbed

Reputation: 46703

When you namespace the route, you're creating URL and path helpers that look like this:

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)

So you can either use those directly in your code (i.e. redirect_to admin_site_path(@site) ), or you can do something like:

redirect_to([:admin, @site])

Upvotes: 1

Related Questions