Module: RSpec::ActiveRecord::StubModels

Included in:
RSpec::ActiveRecord
Defined in:
lib/rspec/active_record/stub_models.rb

Overview

Used for stubbing classes in your tests

Instance Method Summary collapse

Instance Method Details

#create_temporary_table(*args, **options, &block) ⇒ Object

Creates temporary table. Only works correctly if DDL transactions are enabled. Takes same arguments as create_table in ActiveRecord migration.



42
43
44
# File 'lib/rspec/active_record/stub_models.rb', line 42

def create_temporary_table(*args, **options, &block)
  ::ActiveRecord::Base.connection.create_table(*args, **options, &block)
end

#stub_class(name, parent = Object) { ... } ⇒ Object

Stub a class with specific name for testing.

Examples:

stub_class :DummyDecorator, ApplicationDecorator do
  def object = Object.new
end
DummyDecorator.new.object #=> #<Object>

Parameters:

  • name (#to_s)

    Name of stubbed class.

  • parent (Class) (defaults to: Object)

    Parent class of stubbed class.

Yields:

  • Pass the block to further customize the class.



16
17
18
# File 'lib/rspec/active_record/stub_models.rb', line 16

def stub_class(name, parent = Object, &block)
  stub_const(name.to_s, Class.new(parent, &block))
end

#stub_model(name, parent = ApplicationRecord) { ... } ⇒ Object

Stub a model with specific name for testing.

Examples:

stub_model :DummyUser do
  belongs_to :client, optional: true
end
create_temporary_table :dummy_users do |t|
  t.belongs_to :client
end
DummyUser.new.client #=> nil

Parameters:

  • name (#to_s)

    Name of stubbed class.

  • parent (Class) (defaults to: ApplicationRecord)

    Parent class of stubbed class.

Yields:

  • Pass the block to further customize the class.

See Also:



33
34
35
36
37
38
# File 'lib/rspec/active_record/stub_models.rb', line 33

def stub_model(name, parent = ApplicationRecord, &block)
  stub_class(name, parent) do
    self.table_name = name.to_s.tableize
    class_eval(&block) if block
  end
end