How to test a Controller Concern in Rails 4

前端 未结 4 1414
孤独总比滥情好
孤独总比滥情好 2021-01-29 23:18

What is the best way to handle testing of concerns when used in Rails 4 controllers? Say I have a trivial concern Citations.

module Citations
    ex         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 23:44

    I am using a simpler way to test my controller concerns, not sure if this is the correct way but seemed much simpler that the above and makes sense to me, its kind of using the scope of your included controllers. Please let me know if there are any issues with this method. sample controller:

    class MyController < BaseController
      include MyConcern
    
      def index
        ...
    
        type = column_type(column_name)
        ...
      end
    

    end

    my controller concern:

    module MyConcern
      ...
      def column_type(name)
        return :phone if (column =~ /phone/).present?
        return :id if column == 'id' || (column =~ /_id/).present?
       :default
      end
      ...
    
    end
    

    spec test for concern:

    require 'spec_helper'
    
    describe SearchFilter do
      let(:ac)    { MyController.new }
      context '#column_type' do
        it 'should return :phone for phone type column' do
          expect(ac.column_type('phone')).to eq(:phone)
        end
    
        it 'should return :id for id column' do
          expect(ac.column_type('company_id')).to eq(:id)
        end
    
        it 'should return :id for id column' do
          expect(ac.column_type('id')).to eq(:id)
        end
    
        it 'should return :default for other types of columns' do
          expect(ac.column_type('company_name')).to eq(:default)
        end
      end
    end
    

提交回复
热议问题