Module: Lopata::ActiveRecord::Methods

Included in:
Scenario
Defined in:
lib/lopata/active_record.rb

Overview

To be included in Lopata::Scenario. The methods may be used in runtime.

Instance Method Summary collapse

Instance Method Details

#cleanup(*objects) ⇒ Object

Destroy ActiveRecord objects.

Does nothing if ‘keep’ mode is enabled:

Lopata.configure do |c|
  c.keep = true
end

Parameters:

  • objects (Array<ActiveRecord::Base, Array<ActiveRecord::Base>, nil>)

    to be destroyed

See Also:



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/lopata/active_record.rb', line 47

def cleanup(*objects)
  return if Lopata.configuration.keep
  objects.flatten.compact.each do |o|
    begin
      o.reload.destroy!
    rescue ::ActiveRecord::RecordNotFound
      # Already destroyed - skip
    rescue ::ActiveRecord::InvalidForeignKey
      # Possible async job created new relationships (e.g. history records). Try again once.
      o.reload.destroy!
    end
  end
end

#cleanup_later(object) ⇒ Object

Marks object to be destroyed at the end of scenario

Parameters:

  • object (ActiveRecord::Base)

    the object to be destoryed at the end of scenario

Returns:

  • the given object, so chains can be build



79
80
81
82
83
84
# File 'lib/lopata/active_record.rb', line 79

def cleanup_later(object)
  return nil unless object
  @created_objects ||= []
  @created_objects << object
  object
end

#find_created(cls, params) ⇒ ActiveRecord::Base?

Find ActiveRecord object of given class by params. Marks the returned object to be destroyed at the end of scenario.

Examples:

action do
  # UI actions creating the user
  @user = find_created(User, username: 'testuser')
end
it 'created' do
  expect(@user).to_not be_nil
end
# No cleanup needed
# cleanup :user

Parameters:

  • cls (Class)

    active record model class

  • params (Hash)

    options for record finding

Returns:

  • (ActiveRecord::Base, nil)

    the object or nil if not found

See Also:



104
105
106
# File 'lib/lopata/active_record.rb', line 104

def find_created(cls, params)
  cleanup_later cls.where(params).take
end

#reload(*objects) ⇒ Object

Reload ActiveRecord objects

Examples:


# use in steps
reload @a, @b
# instead of
@a.reload; @b.reload

Parameters:

  • objects (Array<ActiveRecord::Base, Array<ActiveRecord::Base>, nil>)

    to be reloaded



71
72
73
# File 'lib/lopata/active_record.rb', line 71

def reload(*objects)
  objects.flatten.compact.each(&:reload)
end