Implicit use of an object in rspec example does not work

I am going to test the get_uniq_id method of the model.

application / models / problems / id_generation.rb

module IdGeneration
  extend ActiveSupport::Concern

  module ClassMethods
    def get_uniq_id
      id = ''
      loop {
        id = generate_id
        break unless Ticket.find_by_token(id)
      }
      id
    end

    def generate_id
      id = []
      "%s-%d-%s-%d-%s".split('-').each{|v| id << (v.eql?('%s') ? generate_characters : generate_digits)}
      id.join('-')
    end

    def generate_digits(quantity = 3)
      (0..9).to_a.shuffle[0, quantity].join
    end

    def generate_characters(quantity = 3)
      ('A'..'Z').to_a.shuffle[0, quantity].join
    end    
  end
end

spec / issues / id_generation_spec.rb

require 'spec_helper'
describe IdGeneration do
  class Dummy
    include IdGeneration::ClassMethods
  end
  subject { Dummy.new }
  it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
end

It gives an error:

 Failure/Error: it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
 NameError:
   undefined local variable or method `get_uniq_id' for #<RSpec::ExampleGroups::IdGeneration:0x00000001808c38>

If I indicate the topic explicitly it { should subject.get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/)}. He works.

Does the topic need to be specified specifically?

0
source share
1 answer

The method invocation method is yes. This method must be called on the object. In this case, it get_uniq_idwill be executed in the context of the current test run, and that is why a tooltip appears.

You can use a shortcut:

it { should respond_to :get_uniq_id }

A similar test will be performed subject.respond_to?(:get_uniq_id). However, a method call needs an explicit receiver.

, , , :

require 'spec_helper'
describe IdGeneration do
  class Dummy
    include IdGeneration::ClassMethods
  end
  subject { Dummy.new }

  def get_uniq_id
    subject.get_uniq_id
  end

  it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
end

, subject:

require 'spec_helper'
describe IdGeneration do
  class Dummy
    include IdGeneration::ClassMethods
  end

  let(:dummy) { Dummy.new }
  subject     { dummy }

  describe "#get_uniq_id" do
    subject { dummy.get_uniq_id }

    it { should match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
  end
end
0

All Articles