【问题标题】:ApplicationController Private method's variable rspec testingApplicationController Private 方法的变量 rspec 测试
【发布时间】:2019-02-13 09:05:39
【问题描述】:

我在 ApplicationController 中制作了这段代码。这是一种在任何要运行的方法开始时运行的方法。我想用 rspec 测试这个方法,想知道性别给出正确的输出还是错误的。

这是代码的路径

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

这是应用程序控制器:

    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-rails rspec ruby-on-rails-5 rspec-rails


    【解决方案1】:

    我会检查在 before_action 中设置的实例变量。它看起来像这样:

    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
    

    【讨论】:

      猜你喜欢
      • 2012-09-26
      • 1970-01-01
      • 2014-11-19
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多