首页 > 解决方案 > ApplicationController Private method's variable rspec testing

问题描述

I have made this code in ApplicationController. This is a method which runs at the start of any method to run. I want to test this method with rspec and want to know that the gender is giving right output or wrong.

this is the route of the code

get ':sex/names/:name_kanji', to: 'names#show'

And this is the application controller:

    class ApplicationController < ActionController::Base
    before_action :check_sex

    private

    def check_sex
        @header_color = nil
        @header_nav_hash = {'other' => nil, 'boy' => nil, 'girl' => nil}
        @page_scoop = params[:sex].presence || 'other'
        unless @page_scoop.match(/^(boy|girl|other)$/) 
            render_404
        end
        if @page_scoop == "boy" || @page_scoop == "girl"
            @gender_base = @page_scoop            
        end
        @header_nav_hash[@page_scoop] = 'is-active'
        @header_color = @page_scoop == 'boy' ? 'is-info' : 'is-danger' if @page_scoop != 'other'
    end

    def render_404
      render template: 'errors/error_404' ,  status: 404 ,  layout: 'application' ,  content_type: 'text/html'
    end

    def render_500
      render  template: 'errors/error_500' ,  status: 500 ,  layout: 'application' ,  content_type: 'text/html'
    end

end

标签: ruby-on-railsrspecruby-on-rails-5rspec-rails

解决方案


I would inspect the instance variables that being set in the before_action. It would look something like this:

describe 'on GET to :show' do
  before do
    get :show, params: { <valid params here> }
  end

  it 'sets @page_scoop' do
    expect(assigns(:page_scoop)).to eq 'boy'
  end
end

推荐阅读