Today I Learned

Mocking database views in Rspec

Sometimes it is a chore to feed database with all data we need for given database view to return results we are after within specs. Fortunately we can utilize temporary tables to mock such database views!

RSpec.configure do |config|
  ActiveRecord::Migration.verbose = false

  config.before(:all, :use_dummy_db_views) do |_example|
    ActiveRecord::Migration.create_table :my_database_view_entries, id: false, force: true do |t|
      t.integer :some_foreign_key      
      t.string :some_name
      t.string :some_code
    end

    MyDatabaseViewModel.table_name = 'my_database_view_entries'
  end

  config.after(:all, :use_dummy_db_views) do |_example|
    MyDatabaseViewModel.table_name = 'orignal_name_of_my_database_view'
    ActiveRecord::Migration.drop_table :my_database_view_entries, force: true    
  end
end

Then it is just a matter of creating simulated view results, i.e. using factories.

# factory
FactoryBot.define do
  factory :my_database_view_model do
    some_foreign_key 10
    some_name 'Iron Man'
    some_code 'IRON'
  end
end

# some spec
it 'some expectation', :use_dummy_db_views do
  create(:my_database_view_model)
  # ...
end