Question

I have a Queues controller and and QueueItems controller in my rails application. In routes I have defined as below match 'queues/:queue_id/next', :to=> 'queueitems#next' In my QueueItems Controller I have a next action and it assigns an instance variable.

def next
@queue = "Regular"
#other stuffs related to regular
end

How do I test this in Rspec. I am pretty very new to Rspec. Please help. I tried like the below

describe QueuesController do
    describe "next " do
      it "routes /queues/:queue_id/next" do
        { :get => "/queues/regular_queue/next" }.should route_to(
          :controller => "queue_items",
          :action => "next",
          :queue_id => "regular_queue",
          :format => "json"
            )
        assigns(:queue).should_not be_nil
        expect(response).to be_success
      end
end

But it is not at all coming inside my next action in controller.

Update #2 spec/controllers/queue_items_controller_spec.rb

require 'spec_helper'
describe QueueItemsController do
        describe 'GET next' do
        it 'assigns @queue' do
          get :next, format: :json
          expect(assigns[:queue]).to eq('regular')
      end
    end
  end

queue_items_controller.rb

def next
   puts "Inside next action..."
    @queue = "regular"

end

routes.rb

  get '/queues/:queue_id/next', :to => 'queue_items#next', :format=>'json'

rake routes

GET  /queues/:queue_id/next(.:format)                                                        queue_items#next {:format=>"json"}
                  /queues/:queue_id/delete(.:format)                                                      queue_items#delete {:method=>:delete, :format=>"json"}
                  /queues/:queue_id/clear(.:format)                                                       queue_items#clear {:format=>"json"}
Was it helpful?

Solution

First of all change match to get or post - it is better to use exactly verb. Let's say it is get.

Action next is in QueueItemsController so test should be in this queue_items_controller_spec.rb file (and in folder spec/controlers).

and test might be similar to

describe QueueItemsController do
  describe "GET next " do

    it "responses json" do
      get :next, format: :json
      expect(response).to be_success
    end

    it "does not response html" do
      get :next, format: :html
      expect(response).not_to be_success # or define more exactly response
    end

    it 'assigns @queue' do
      get :next, format: :json
      expect(assigns[:queue]).to eq('Regular')
    end

  end
end

if you would like to test your routes you should follow this articles:

https://www.relishapp.com/rspec/rspec-rails/v/2-14/docs/routing-specs https://www.relishapp.com/rspec/rspec-rails/docs/routing-specs/route-to-matcher

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top