A common example of a singular resource is a user dashboard. A singular resource allows you to create a route to a single item without an id. Since you’ll typically have only one user dashboard you wouldn’t want to have to specify the id of the dashboard you want to access.

resource :dashboard, only: [:show]

The route info is:

dashboard GET
/dashboard(.:format)
dashboards#show

The singular resource corresponds to a plural controller, so that both singular and plural routes can map to the same controller:

class DashboardsController < ApplicationController
  
  def show
    @user = current_user
  end
  
end

These tests use the RSpec framework and Fabrication gem:

require 'spec_helper'

describe DashboardsController do
    
  context 'with authenticated user' do
    let(:user) { Fabricate(:user) }
    before do
      session[:user_id] = user.id
    end
    describe 'GET show' do
      it 'assigns @user' do
        get :show
        expect(assigns(:user)).to eq(user)
      end
      it 'renders the show template' do
        get :show
        expect(response).to render_template('show')
      end
    end
  end
end

Tags: ,

In categories: Rails, web development

COMMENTS

LEAVE A REPLY

Only the name field is required. Your email will not be published.