db_migration.rb 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # require all database migrations so we can test them without manual require
  2. Rails.root.join('db', 'migrate').children.each do |migration|
  3. require migration.to_s
  4. end
  5. module DbMigrationHelper
  6. # Provides a helper method to execute a migration for the current class.
  7. # Make sure to define type: :db_migration in your RSpec.describe call.
  8. #
  9. # @param [Symbol] direction the migration should take (:up or :down)
  10. # @yield [instance] Yields the created instance of the
  11. # migration to allow expectations or other changes to it
  12. #
  13. # @example
  14. # migrate
  15. # @example
  16. # migrate(:down)
  17. #
  18. # @return [nil]
  19. def migrate(direction = :up)
  20. instance = described_class.new
  21. yield(instance) if block_given?
  22. instance.suppress_messages do
  23. instance.migrate(direction)
  24. end
  25. end
  26. def self.included(base)
  27. # Execute in RSpec class context
  28. base.class_exec do
  29. # This method simulates a system that is is already initialized
  30. # aka `Setting.exists?(name: 'system_init_done')`
  31. # It's possible to simulate a not yet initialized system by adding the
  32. # meta tag `system_init_done` to `false` to the needing example:
  33. #
  34. # @example
  35. # it 'does stuff in an unitialized system', system_init_done: false do
  36. #
  37. before(:each) do |example|
  38. initialized = example.metadata.fetch(:system_init_done, true)
  39. system_init_done(initialized)
  40. end
  41. end
  42. end
  43. end
  44. RSpec.configure do |config|
  45. config.include DbMigrationHelper, type: :db_migration
  46. end