Class: FactoryBurgers::SequenceCheater

Inherits:
BasicObject
Defined in:
lib/factory_burgers/sequence_cheater.rb

Overview

A SequenceCheater is able to take the block associated with a factory’s attribute and discover if it uses a sequence (specifically, if it calls ‘generate`). It does this by evaluting the block in its own context, where the `generate` method has been defined to save the name it was called with.

For example, in the following factory:

FactoryBot.define do

factory :foo do
  bar { generate :baz }
end

end

We can discover the ‘bar` attribute of the factory, and throgh some slightly dangerous non-public access (it’s Ruby, after all) we can get the block defined as ‘{ generate :baz }`. We then call that block on a SequenceCheater, which simply records that `generate` was called with the name `:baz`.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSequenceCheater

Returns a new instance of SequenceCheater.



22
23
24
# File 'lib/factory_burgers/sequence_cheater.rb', line 22

def initialize
  @sequence_names = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(_name, *_args) ⇒ Object

We explicitly want to swallow and do nothing on method_missing; We only want to detect occurences of ‘generate`.



32
33
34
# File 'lib/factory_burgers/sequence_cheater.rb', line 32

def method_missing(_name, *_args)
  # do nothing, do not fail
end

Instance Attribute Details

#sequence_namesObject (readonly)

Returns the value of attribute sequence_names.



20
21
22
# File 'lib/factory_burgers/sequence_cheater.rb', line 20

def sequence_names
  @sequence_names
end

Instance Method Details

#generate(name = nil, *_args, &_blk) ⇒ Object



26
27
28
# File 'lib/factory_burgers/sequence_cheater.rb', line 26

def generate(name = nil, *_args, &_blk)
  @sequence_names |= [name] unless name.nil?
end