diff --git a/doc/configuration.md b/doc/configuration.md index 3210bb85..beb0b877 100644 --- a/doc/configuration.md +++ b/doc/configuration.md @@ -207,18 +207,20 @@ config.namespace = nil User.table_name # => "users" ``` -How you configure `config.namespace` depends on your AWS account architecture: - -* *Shared AWS accounts* — when development, test, and staging environments share an AWS account, dynamic namespaces prevent data collisions: - ```ruby - config.namespace = "myapp_#{ENV.fetch('APP_ENV', 'development')}" - ``` -* *Dedicated AWS accounts* — when production and staging run in separate AWS accounts (the recommended AWS security architecture), table name prefixes are redundant. Setting `config.namespace = nil` keeps table names simple (`users`, `orders`). -* *Parallel test runners* — when executing tests concurrently across multiple workers (such as `parallel_tests` or multiple CI containers), incorporate the process or worker ID to isolate tables: - ```ruby - worker_id = ENV['TEST_ENV_NUMBER'] || Process.pid - config.namespace = "myapp_test_#{worker_id}" - ``` +When multiple environments (e.g. staging and production) share an AWS account, include the environment name in `config.namespace` to prevent table collisions: + +```ruby +config.namespace = "myapp_#{ENV.fetch('APP_ENV', 'development')}" +``` + +When each environment runs in a dedicated AWS account, table name prefixes are redundant—setting `config.namespace = nil` keeps table names simple (`users`, `orders`). + +When a test suite is split and run in parallel across multiple processes, include a process ID in `config.namespace` so each process uses its own tables: + +```ruby +worker_id = ENV['TEST_ENV_NUMBER'] || Process.pid +config.namespace = "myapp_test_#{worker_id}" +``` For model-level table name overrides and ARN mapping, see [Table Mapping & Provisioning](modeling_and_schema/table_mapping_and_provisioning.md). diff --git a/doc/getting_started.md b/doc/getting_started.md index 3b39169d..f9395134 100644 --- a/doc/getting_started.md +++ b/doc/getting_started.md @@ -10,16 +10,13 @@ DynamoDB stores data in *tables*, which contain *items* (analogous to rows or do Unlike relational databases, DynamoDB tables do not enforce a column schema. The table definition specifies only the *primary key*, which uniquely identifies each item. All other attributes are dynamic—different items in the same table can carry different attributes, and an attribute only exists on an item when assigned a value. -The primary key is composed of one or two attributes: - -* A *simple primary key* consists of a single attribute serving as the *partition key* (historically called a *hash key*). The value of this attribute must be unique across the entire table. -* A *composite primary key* is composed of two attributes: a *partition key* attribute and a *sort key* attribute (historically called a *range key*). The combination of both values forms the unique item identifier—multiple items can share the same partition key value as long as their sort key values differ. +A primary key can be either simple or composite. A *simple primary key* consists of a single *partition key* attribute (historically called a *hash key*), whose value must be unique across the entire table. A *composite primary key* combines a *partition key* with a *sort key* (historically called a *range key*); together they uniquely identify an item, so multiple items can share the same partition key value as long as their sort key values differ. How you access data depends directly on these key attributes: * A *point lookup* retrieves a single item directly by its primary key. * A *query operation* retrieves items matching an exact partition key, optionally filtered by sort key conditions. -* A *scan operation* reads every item in the table whenever a search does not specify a partition key. +* A *scan operation* reads every item in the table when no partition key is specified. ## Key Differences from Relational Databases @@ -31,20 +28,20 @@ In PostgreSQL or MySQL, table schemas define every column and data type upfront. Primary keys also behave differently during writes: -* DynamoDB does not provide auto-incrementing integer sequences (`SERIAL` or `AUTO_INCREMENT`). Dynamoid automatically generates UUIDs for string partition keys, but integer partition keys and sort keys must be assigned by the application. -* An item's primary key (both the partition key and sort key) is strictly immutable once written. Changing an item's primary key requires creating a new item and deleting the original. -* Every write, update, and delete operation must target an item by its exact primary key—there is no equivalent to SQL's `UPDATE ... WHERE` or `DELETE ... WHERE` to modify or remove multiple rows matching arbitrary attribute conditions in a single statement. +* DynamoDB does not auto-generate primary keys or sequences; key values must always be provided on write. +* Primary keys are immutable once written; changing a key requires creating a new item and deleting the original. +* Updates and deletes must target an exact primary key—there is no equivalent to `UPDATE ... WHERE` or `DELETE ... WHERE`. ### Querying and Indexing Relational databases provide an expressive query engine with automated index planning, dynamic sorting, random-access pagination, and server-side aggregation. DynamoDB trades this flexibility for predictable, single-digit millisecond latency at any scale, resulting in several fundamental constraints: * Fast queries require an equality condition on the *partition key*, optionally refined with range conditions on the *sort key*. -* To filter efficiently by other attributes, you must define a secondary index (where those attributes serve as the index key) and target that index explicitly by name. -* Results can only be sorted by the sort key defined on the table or index—there is no arbitrary `ORDER BY` on non-key attributes. -* Pagination is forward-only. Unlike relational databases that support numeric `OFFSET` to jump to arbitrary pages, DynamoDB only allows traversing results sequentially from one page to the next, with no backward pagination. -* There is no `GROUP BY` clause or database-level aggregation (`SUM`, `AVG`, `MIN`, `MAX`). Finding totals or summary metrics requires calculating them in application code or maintaining pre-computed counter attributes with atomic increments. -* Unlike relational databases that guarantee immediate read-after-write consistency, DynamoDB reads (point lookups and queries) are *eventually consistent* by default—a read right after a write might briefly return stale data. When up-to-date data is required, you can request a *strongly consistent read* to guarantee seeing the latest write. +* Filtering efficiently by other attributes requires defining a secondary index with those attributes as the index key. +* Results can only be sorted by the sort key—there is no arbitrary `ORDER BY` on non-key attributes. +* Result sets are traversed forward using cursors—there is no numeric `OFFSET` to skip a given number of items. +* There is no `GROUP BY` or server-side aggregation (`SUM`, `AVG`, `MIN`, `MAX`); totals must be computed in application code. +* Reads are *eventually consistent* by default and may briefly return stale data after a write unless you request a *strongly consistent read*. ### Relationships and Joins @@ -62,9 +59,9 @@ DynamoDB does not support interactive transactions or pessimistic locking. While DynamoDB also enforces several hard operational limits: -* Items cannot exceed 400 KB in total size, including all attribute names and values combined. Larger payloads or file attachments should be offloaded to external storage. -* A single query or scan operation returns at most 1 MB of data before pausing, requiring pagination even if a requested item limit has not yet been met. -* Native batch writes and deletes are capped at 25 items per request, while batch reads and transactions are limited to 100 items. +* An item cannot exceed 400 KB in total size ([including attribute names and values](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CapacityUnitCalculations.html)). +* A single query or scan request returns at most 1 MB of data per page. +* Batch writes and deletes are capped at 25 items per request; batch reads and transactions are capped at 100 items. ## The Active Record Pattern in Dynamoid @@ -126,11 +123,11 @@ If a DynamoDB item contains attributes not declared in your Ruby model, Dynamoid ### Conventions and Defaults -Dynamoid follows *convention over configuration*, so a conventional model only needs to declare its fields: +Dynamoid follows *convention over configuration*, so a model only needs to declare its fields: -* Table names are automatically derived from the pluralized class name (`User` → `users`), prefixed by any configured namespace (`config.namespace`). -* The primary key defaults to a partition key named `id` of type `string`. When saving a new model, Dynamoid assigns an auto-generated UUID string if no `id` is specified. -* Timestamps are maintained automatically: Dynamoid generates `created_at` and `updated_at` datetime fields on every model by default. +* Table names are derived from the pluralized class name (`User` → `users`) and prefixed with `config.namespace`. +* The primary key defaults to a string partition key named `id`, populated with a random UUID on save if unset. +* Models automatically include and maintain `created_at` and `updated_at` datetime fields. > [!NOTE] > To customize these defaults—such as specifying a custom table name, configuring a custom partition key name or type, or declaring a sort key for a composite primary key—refer to [Table Mapping & Provisioning](modeling_and_schema/table_mapping_and_provisioning.md). diff --git a/doc/modeling_and_schema/associations.md b/doc/modeling_and_schema/associations.md index 8b3ee5e9..70a2cadc 100644 --- a/doc/modeling_and_schema/associations.md +++ b/doc/modeling_and_schema/associations.md @@ -751,8 +751,8 @@ Instead of querying a secondary index by foreign key, Dynamoid caches the partit This storage strategy involves two deliberate simplifications: -* *Sets for all associations* — to keep the implementation uniform across all macros, Dynamoid uses a `_ids` set attribute even for `has_one` and `belongs_to` associations, where the set holds only a single partition key. -* *Simple primary keys only* — because DynamoDB sets can only store scalar values, cached IDs only store partition keys. Models with composite primary keys (partition key and sort key) cannot declare or participate in associations. +* *Sets for all associations* — `has_one` and `belongs_to` also use an `_ids` set attribute, holding a single partition key. +* *Simple primary keys only* — because DynamoDB sets only hold scalar values, models with composite primary keys cannot use associations. For `Author` (`has_many :books`) and `Book` (`belongs_to :author`), linking models stores the following attributes on their DynamoDB items: @@ -772,9 +772,9 @@ book.author_id # => "f41a8c..." Storing the foreign key as a scalar attribute is necessary if you plan to index it with a Global Secondary Index, as DynamoDB does not allow indexing Set attributes. -Relying on cached IDs rather than secondary indexes creates two distinct trade-offs: +Relying on cached IDs rather than secondary indexes creates two trade-offs: -* *Item size growth* — every linked model adds an ID to the parent item's `_ids` set. For high-cardinality relationships, this expands the item's payload, consumes more read and write capacity, and can eventually hit DynamoDB's hard 400 KB item size limit. -* *Outdated cached IDs* — because references are maintained entirely by Dynamoid in application code, deleting an item outside Dynamoid (or via class-level `Model.delete(id)`) leaves stale, orphaned IDs in the associated model's cached set. +* *Item size growth* — each linked model adds an ID to `_ids`, increasing payload size toward the 400 KB item limit. +* *Outdated cached IDs* — creating or deleting items via class-level persistence methods (such as `import`, `upsert`, `delete`, or `delete_all`) or outside Dynamoid does not update the associated model's cached ID set. {{#include ../_includes/feedback.md}} diff --git a/doc/modeling_and_schema/fields_and_data_types.md b/doc/modeling_and_schema/fields_and_data_types.md index b1fa6650..bba72867 100644 --- a/doc/modeling_and_schema/fields_and_data_types.md +++ b/doc/modeling_and_schema/fields_and_data_types.md @@ -696,10 +696,10 @@ Dynamoid tracks changes in custom type attributes to determine which fields to u To detect these changes, Dynamoid supports two comparison strategies: -* *Serialized comparison (default)* — Dynamoid serializes the attribute value and compares the serialized result against the database state. This works out of the box without requiring the custom type to implement `#==`. The trade-off is performance: serializing values whenever checking for changes (such as calling `changed?` or saving) incurs extra overhead. -* *In-memory comparison* — Dynamoid compares the Ruby objects directly in memory using `#==`, skipping serialization entirely. +* *Serialized comparison (default)* — serializes the attribute value and compares the result against the database state. +* *In-memory comparison* — compares the Ruby objects directly in memory using `#==`. -To enable in-memory comparison, pass `comparable: true` in the field declaration: +Serialized comparison works out of the box without requiring `#==`, but serializing values whenever checking for changes (such as calling `changed?` or saving) incurs extra overhead. To enable in-memory comparison instead, pass `comparable: true` in the field declaration: ```ruby class Order @@ -845,20 +845,21 @@ The following table catalogs all configuration options that govern attribute ser ### Historical Background -Several storage configuration options exist because Amazon DynamoDB's data model evolved significantly after its initial release in 2012. As DynamoDB introduced new capabilities, Dynamoid added configuration options to adopt the new database behavior while preserving backward compatibility for existing data: +Several storage configuration options exist because Amazon DynamoDB's data model evolved significantly after its initial release in 2012. As DynamoDB introduced new capabilities, Dynamoid added configuration options to adopt the new database behavior while preserving backward compatibility for existing data. -* *The Original 2012 Data Model* — DynamoDB launched supporting only strings and numbers, with binary data added later that year. It had no concept of booleans, nulls, lists, or maps. Dynamoid originally stored booleans as `'t'` and `'f'` strings, and omitted or removed attributes assigned `nil`. -* *Document Types & Null Values (October 2014)* — AWS introduced native booleans, explicit nulls, lists, and maps. Dynamoid introduced `store_boolean_as_native` to support native booleans while maintaining compatibility with legacy data, and `store_attribute_with_nil_value` to optionally persist explicit null attributes. -* *Empty String Support (May 2020)* — DynamoDB originally rejected empty strings, so Dynamoid automatically converted empty strings to `nil`. After DynamoDB added support for empty strings in 2020, Dynamoid introduced `store_empty_string_as_nil` (defaulting to `true` for backward compatibility) to allow applications to persist empty strings as-is. +When DynamoDB launched in 2012, it supported only strings and numbers (with binary data added later that year) and had no concept of booleans, nulls, lists, or maps. Dynamoid originally stored booleans as `'t'` and `'f'` strings, and omitted or removed attributes assigned `nil`. + +In October 2014, DynamoDB added native booleans, explicit nulls, and document types (lists and maps). Dynamoid added `store_boolean_as_native` to support native booleans while maintaining compatibility with legacy data, and `store_attribute_with_nil_value` to optionally persist explicit null attributes. + +In May 2020, DynamoDB added support for empty strings. Because DynamoDB originally rejected empty strings, Dynamoid had always converted them to `nil`. Dynamoid introduced `store_empty_string_as_nil` (defaulting to `true` for backward compatibility) so applications can opt into persisting empty strings as-is. ### Nil Attributes When a model attribute has a `nil` value, Dynamoid can store it in DynamoDB in two ways: by omitting the attribute entirely, or by persisting an explicit `NULL` value. By default, Dynamoid omits or removes attributes with `nil` values, preserving the original DynamoDB behavior from before native `NULL` support was added. -Omitting `NULL` attributes provides two advantages: +Omitting `nil` attributes saves storage and throughput: because both attribute names and values contribute to item size in DynamoDB, writing explicit `NULL` values increases payload size and consumes extra read and write capacity. -* *Storage and throughput efficiency* — In DynamoDB, attribute names and values both contribute to item size. Storing explicit `NULL` values increases item size and consumes additional read and write throughput, whereas omitting `nil` attributes conserves capacity. -* *Index compatibility and sparse indexes* — DynamoDB index keys (partition keys and sort keys for tables and secondary indexes) only support String, Number, or Binary types; they strictly prohibit `NULL`. Persisting an explicit `NULL` to an indexed attribute causes DynamoDB to raise a `ValidationException`. Omitting `nil` attributes prevents this error automatically and enables sparse secondary indexes. +Omitting `nil` attributes is also required for secondary index keys. DynamoDB index keys only accept String, Number, or Binary values and reject `NULL`—persisting an explicit `NULL` to an indexed attribute raises an error. Omitting `nil` attributes avoids this error and allows secondary indexes to act as sparse indexes. If your application or external integrations require explicit null values, enable `store_attribute_with_nil_value`: @@ -893,12 +894,7 @@ user.reload.settings ### Time Zones -For `:datetime` fields, Dynamoid is time zone-aware and separates the time zone used in your application from the time zone used for database storage: - -* `Dynamoid.config.application_timezone` (default `:utc`) — controls how `DateTime` instances are presented in your application (`:utc`, `:local`, or a named zone like `"America/New_York"`). In Rails applications, set this to `:local` or `Time.zone.name`. -* `Dynamoid.config.dynamodb_timezone` (default `:utc`) — controls the time zone used when writing timestamps to DynamoDB as ISO-8601 strings. - -Strings without an explicit time zone offset are interpreted in `application_timezone`, normalized to `dynamodb_timezone` when stored, and converted back to `application_timezone` when loaded: +For `:datetime` fields, Dynamoid separates the time zone used in your application from the time zone used when storing timestamps as ISO-8601 strings in DynamoDB, configured via [`application_timezone` and `dynamodb_timezone`](../configuration.md#configapplication_timezone-and-configdynamodb_timezone): ```ruby Dynamoid.configure do |config| @@ -906,20 +902,20 @@ Dynamoid.configure do |config| config.dynamodb_timezone = :utc config.store_datetime_as_string = true end +``` -order = Order.create!(placed_at: '2026-10-15 16:00:00') +Strings without an explicit time zone offset are interpreted in `application_timezone` when assigned, normalized to `dynamodb_timezone` when stored, and converted back to `application_timezone` when loaded: -order.placed_at -# => 2026-10-15T16:00:00-04:00 +```ruby +order = Order.create!(placed_at: '2026-10-15 16:00:00') +order.placed_at # => 2026-10-15T16:00:00-04:00 +order.reload.placed_at # => 2026-10-15T16:00:00-04:00 # DynamoDB item attribute: -# "placed_at": "2026-10-15T20:00:00+00:00" (normalized to UTC) - -order.reload.placed_at -# => 2026-10-15T16:00:00-04:00 +# "placed_at": "2026-10-15T20:00:00+00:00" ``` -When storing timestamps as strings, Dynamoid normalizes values to `dynamodb_timezone` (UTC by default). Because ISO-8601 strings sort alphabetically, uniform normalization ensures range queries (`between`, `gt`, `lt`) and chronological sorting work reliably. (Numeric timestamps are stored as epoch seconds and are inherently UTC.) +When storing timestamps as strings, Dynamoid normalizes values to `dynamodb_timezone` (UTC by default). Because ISO-8601 strings sort alphabetically, uniform normalization ensures range queries (`between`, `gt`, `lt`) and chronological sorting work reliably. ### YAML Deserialization diff --git a/doc/modeling_and_schema/table_mapping_and_provisioning.md b/doc/modeling_and_schema/table_mapping_and_provisioning.md index 917c6c92..23a3b51f 100644 --- a/doc/modeling_and_schema/table_mapping_and_provisioning.md +++ b/doc/modeling_and_schema/table_mapping_and_provisioning.md @@ -303,9 +303,6 @@ class Session end ``` -The `expires` option controls two distinct behaviors: - -* *On save* — Dynamoid sets the TTL attribute to the current Unix timestamp plus `:after` seconds whenever the attribute value is `nil`. -* *On table creation* — Dynamoid enables TTL on the backing DynamoDB table for the specified attribute. If your table is provisioned externally (such as via Terraform or CloudFormation), you must enable TTL on the DynamoDB table in your infrastructure configuration. +When saving a model, Dynamoid sets the TTL attribute to the current Unix timestamp plus `:after` seconds whenever the attribute value is `nil`. When creating the table, Dynamoid also enables TTL on the backing DynamoDB table for the specified attribute (if the table is provisioned externally, such as via Terraform or CloudFormation, you must enable TTL in your infrastructure configuration). {{#include ../_includes/feedback.md}} diff --git a/doc/testing.md b/doc/testing.md index 25f33e85..68010305 100644 --- a/doc/testing.md +++ b/doc/testing.md @@ -1,60 +1,89 @@ # Testing -Running automated tests with Dynamoid requires a deliberate testing strategy across several fronts: selecting an execution environment—such as a local emulator or a dedicated AWS sandbox account—preventing accidental data loss in remote environments, tuning configuration for local execution speed, and managing table lifecycles without database transactions. +Running automated tests with Dynamoid requires configuring a dedicated test environment—typically targeting a local emulator with an isolated table namespace—guarding against accidental changes to remote or non-test tables, and managing table lifecycles and item cleanup without database transactions. ## Configuration -When running tests against a local emulator (such as DynamoDB Local or LocalStack), configure Dynamoid in `config/environments/test.rb` or `spec/support/dynamoid.rb` to target the local endpoint and tune settings for test execution: +When running tests against a local emulator (such as DynamoDB Local or LocalStack), configure `config.endpoint` in your test setup (such as `config/environments/test.rb`, `spec/support/dynamoid.rb`, or `test/test_helper.rb`) to route requests to the local service instead of AWS: ```ruby Dynamoid.configure do |config| - config.endpoint = ENV.fetch('DYNAMODB_ENDPOINT', 'http://localhost:8000') + config.endpoint = 'http://localhost:8000' +end +``` + +Because the AWS SDK requires a region and credentials even when connecting to a local emulator, configure dummy values if they are not already present in the environment (such as in CI containers): - worker_id = ENV['TEST_ENV_NUMBER'] || Process.pid - config.namespace = "myapp_test_#{worker_id}" +```ruby +config.region = 'us-west-2' +config.access_key = 'test' +config.secret_key = 'test' +``` - config.sync_retry_wait_seconds = 0 - config.sync_retry_max_times = 5 +To prevent test runs from overwriting or dropping development tables on the same emulator, configure a dedicated `config.namespace` for the test environment. When running tests in parallel across multiple processes, append an environment variable containing a unique worker identifier (such as `ENV['TEST_ENV_NUMBER']`) so each process operates on its own tables: - config.logger = false - config.error_on_scan = true -end +```ruby +config.namespace = "myapp_test#{ENV['TEST_ENV_NUMBER']}" +``` + +Outside Rails (where Dynamoid uses `Rails.logger`), `config.logger` defaults to `$stdout` at `Logger::INFO` level, printing every database operation into the test output. To silence routine logs while keeping warnings and errors visible, raise the log level: + +```ruby +config.logger.level = Logger::WARN +``` + +Alternatively, redirect logs to a file or disable logging: + +```ruby +config.logger = Logger.new('log/test.log') +# or +config.logger = false ``` -Because local emulators create tables immediately, setting `sync_retry_wait_seconds = 0` eliminates the default 2-second polling delay. Suffixing `config.namespace` with `ENV['TEST_ENV_NUMBER']` isolates tables across parallel test workers (such as `parallel_tests`), and `config.error_on_scan = true` fails fast if a query accidentally falls back to a full-table scan. +To catch accidental full-table scans during test runs before they reach production, enable `config.error_on_scan` so Dynamoid raises `Dynamoid::Errors::ScanProhibited` whenever `where` conditions trigger a `Scan` operation: + +```ruby +config.error_on_scan = true +``` ## Safety Guards -To prevent test runs from accidentally modifying staging or production tables, add a guard in your test helper (`spec/support/dynamoid.rb` or `test/test_helper.rb`) to verify that the suite is running in the `test` environment: +To prevent test runs from accidentally modifying or dropping development, staging, or production tables, add a guard in your test helper to verify that `Dynamoid.config.namespace` is set to a test namespace: ```ruby -env = ENV['APP_ENV'] || ENV['RACK_ENV'] || (Rails.env if defined?(Rails)) -raise 'Tests must run strictly in the test environment!' unless env == 'test' +unless Dynamoid.config.namespace.to_s.include?('test') + raise "Refusing to run tests with non-test namespace: #{Dynamoid.config.namespace.inspect}" +end ``` -When your test suite runs against a local emulator, also verify that `Dynamoid.config.endpoint` points to a local address rather than remote AWS: +When your test suite runs against a local emulator, also verify that `Dynamoid.config.endpoint` points to a local host rather than remote AWS: ```ruby -unless Dynamoid.config.endpoint&.start_with?('http://localhost', 'http://127.0.0.1', 'http://localstack') - raise 'Expected Dynamoid to point to a local emulator, but found a remote endpoint!' +host = URI(Dynamoid.config.endpoint.to_s).host +unless ['localhost', '127.0.0.1'].include?(host) + raise "Refusing to run tests against non-local endpoint: #{Dynamoid.config.endpoint.inspect}" end ``` ## Test Suite Integration -Because DynamoDB does not support rollbackable transactions, test suites cannot isolate test cases by rolling back database state. Instead, test isolation requires managing table lifecycles and clearing stored items between test runs. Dynamoid provides `Dynamoid::TestHelper` to manage provisioning, truncation, and resets. +Because DynamoDB does not support rollbackable transactions, test suites cannot isolate tests by rolling back database state; instead, use `Dynamoid::TestHelper` to provision tables and clear items between tests. To provision missing tables once before the test suite starts (or only for specific models when running a subset of tests), call `create_tables`: ```ruby Dynamoid::TestHelper.create_tables +# or Dynamoid::TestHelper.create_tables(User, Post) ``` +If your models live outside `./app/models`, configure [`config.models_dir`](configuration.md#configmodels_dir) to point to their directory—when called without arguments, `create_tables` only creates tables for models in that directory. + To clear stored items between individual tests while keeping the tables intact, call `truncate_tables`: ```ruby Dynamoid::TestHelper.truncate_tables +# or Dynamoid::TestHelper.truncate_tables(User, Post) ``` @@ -64,6 +93,8 @@ Because `create_tables` skips tables that already exist, changing a model's prim Dynamoid::TestHelper.drop_tables ``` +Running `drop_tables` before every test suite run guarantees a fresh schema, while omitting it (or gating it behind an environment variable) avoids recreating unchanged tables on every local test run. + ### RSpec In projects using RSpec, configure table lifecycle hooks in `spec/support/dynamoid.rb` (or `spec/spec_helper.rb`): @@ -83,7 +114,7 @@ end ### Minitest -In projects using Minitest, add the equivalent lifecycle hooks to `test/test_helper.rb`: +In projects using Minitest (or `ActiveSupport::TestCase` in Rails), add the equivalent lifecycle hooks to `test/test_helper.rb`: ```ruby Dynamoid::TestHelper.drop_tables @@ -95,11 +126,8 @@ class Minitest::Test Dynamoid::TestHelper.truncate_tables end end -``` - -In Rails applications using `ActiveSupport::TestCase`, use the declarative `setup` block instead: -```ruby +# or in Rails: class ActiveSupport::TestCase setup do Dynamoid::TestHelper.truncate_tables