Rails & RSpec - Testing Concerns class methods

前端 未结 5 881
面向向阳花
面向向阳花 2020-12-14 17:09

I have the following (simplified) Rails Concern:

module HasTerms
  extend ActiveSupport::Concern

  module ClassMethods
    def optional_agreement
      # At         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 17:48

    Building on Aaron K's excellent answer here, there are some nice tricks you can use with described_class that RSpec provides to make your methods ubiquitous and make factories work for you. Here's a snippet of a shared example I recently made for an application:

    shared_examples 'token authenticatable' do
      describe '.find_by_authentication_token' do
        context 'valid token' do
          it 'finds correct user' do
            class_symbol = described_class.name.underscore
            item = create(class_symbol, :authentication_token)
            create(class_symbol, :authentication_token)
    
            item_found = described_class.find_by_authentication_token(
              item.authentication_token
            )
    
            expect(item_found).to eq item
          end
        end
    
        context 'nil token' do
          it 'returns nil' do
            class_symbol = described_class.name.underscore
            create(class_symbol)
    
            item_found = described_class.find_by_authentication_token(nil)
    
            expect(item_found).to be_nil
          end
        end
      end
    end
    

提交回复
热议问题