Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add `spree rspec` command to run tests in web container (#14285)
Damian Legawiec319c32cba248
diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdxindex 13709d5624..a17f6e1b86 100644--- a/docs/developer/cli/quickstart.mdx+++ b/docs/developer/cli/quickstart.mdx@@ -264,6 +264,19 @@ spree routes -c Spree::Api::V3::Store::ProductsController # Filter by controllspree routes --expanded```+### `spree rspec`++Run the RSpec test suite inside the web container with `RAILS_ENV=test`, so tests hit the `spree_test` database — never your development data. Everything after `rspec` passes through, so file paths, line numbers, and flags work as usual.++```bash+spree rspec # full suite+spree rspec spec/models/spree/brand_spec.rb # one file+spree rspec spec/models/spree/brand_spec.rb:15 # one example+spree rspec --format documentation+```++Before the first run, create the test database with `spree rails db:test:prepare`. See the [Testing tutorial](/developer/tutorial/testing) for writing specs.+## Running things inside the containerThese are passthrough commands — anything after the subcommand reaches the inner Rails/Bundle/Rake invocation as-is. Useful for ad-hoc commands that don't have a dedicated wrapper.diff --git a/docs/developer/tutorial/testing.mdx b/docs/developer/tutorial/testing.mdxindex 1ff149fc6f..80a650c661 100644--- a/docs/developer/tutorial/testing.mdx+++ b/docs/developer/tutorial/testing.mdx@@ -589,25 +589,36 @@ expect(page).to have_content('Success!')## Running Tests-In the Docker flow the container's `DATABASE_URL` points at the development database, so tests need two overrides: a dedicated test database, and DatabaseCleaner's opt-in for non-localhost database hosts (its safeguard against cleaning a database it doesn't own). One-time test database setup:+### Prepare the test database-```bash Spree CLI (Docker) — one-time setup-spree exec env RAILS_ENV=test DATABASE_URL=postgres://postgres@postgres:5432/spree_test bin/rails db:prepare+Tests run against a dedicated `spree_test` database, so your development data is never touched. Create it and load the schema once:++<CodeGroup>++```bash Spree CLI (Docker)+spree rails db:test:prepare+```++```bash Without Spree CLI+bin/rails db:test:prepare```-Then run tests:+</CodeGroup>++You rarely need to run this again — `rails_helper.rb` re-syncs the test schema automatically when you add migrations. It's the command to reach for when the test database gets into a broken or out-of-sync state.++### Run the suite++`spree rspec` runs `bundle exec rspec` inside the web container with `RAILS_ENV=test`. Everything after `rspec` is passed through, so file paths, line numbers, and flags work as usual:<CodeGroup>```bash Spree CLI (Docker)-# Define once per shell (or add as an alias):-alias spree-rspec='spree exec env RAILS_ENV=test DATABASE_URL=postgres://postgres@postgres:5432/spree_test DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true bundle exec rspec'--spree-rspec # all tests-spree-rspec spec/models/spree/brand_spec.rb # specific file-spree-rspec spec/models/spree/brand_spec.rb:15 # specific test-spree-rspec --format documentation # documentation format-spree-rspec spec/features/ # only feature tests+spree rspec # all tests+spree rspec spec/models/spree/brand_spec.rb # specific file+spree rspec spec/models/spree/brand_spec.rb:15 # specific test+spree rspec --format documentation # documentation format+spree rspec spec/features/ # only feature tests``````bash Without Spree CLI@@ -620,6 +631,27 @@ bundle exec rspec spec/features/ # only feature tests</CodeGroup>+<Accordion title="Troubleshooting: DatabaseCleaner refuses a remote database URL, or tests hit the development database">++Projects scaffolded before July 2026 set `DATABASE_URL` in `docker-compose.dev.yml`. A URL overrides `config/database.yml` for **every** Rails environment, so in-container tests pointed at the development database and tripped DatabaseCleaner's remote-URL safeguard. Two small changes bring an older project up to date:++1. In `docker-compose.dev.yml`, replace the `DATABASE_URL` entry under `environment:` with host/username parts, so each Rails environment resolves its own database from `database.yml`:++```yaml+ DATABASE_HOST: postgres+ DATABASE_USERNAME: postgres+```++2. In `spec/rails_helper.rb`, force the test environment — the dev container bakes in `RAILS_ENV=development`:++```ruby+ENV['RAILS_ENV'] = 'test'+```++Then restart the stack (`Ctrl+C` and `spree dev`) so the container picks up the new environment.++</Accordion>+## Best Practices<CardGroup cols={2}>@@ -689,6 +721,7 @@ spec/* [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface* [Extending Core Models](/developer/tutorial/extending-models) - Connecting Brands to Products* [API Tutorial](/developer/tutorial/api) - Creating Brand API endpoints+* [Spree CLI](/developer/cli/quickstart) - `spree rspec` and the other dev workflow commands* [RSpec Documentation](https://rspec.info/documentation/) - Official RSpec docs* [Factory Bot Documentation](https://github.com/thoughtbot/factory_bot/blob/main/GETTING_STARTED.md) - Factory Bot guidediff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.mdindex b837012224..6c2b3b216d 100644--- a/packages/cli/CHANGELOG.md+++ b/packages/cli/CHANGELOG.md@@ -1,5 +1,11 @@# @spree/cli+## 2.3.8++### Patch Changes++- Add `spree rspec` — run the RSpec suite inside the web container without spelling out `spree bundle exec rspec`. Everything after `rspec` is forwarded verbatim (`spree rspec spec/models/spree/brand_spec.rb:15`, `spree rspec --format documentation`), `RAILS_ENV=test` is forced so tests always hit the test database, and when the stack is down the command falls back to a one-off container that cold-starts postgres first.+## 2.3.7### Patch Changesdiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 775724b1e3..6cbfe82381 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -88,6 +88,19 @@ Open an interactive Rails console inside the running container.spree console```+### `spree rspec`++Run the RSpec test suite inside the web container with `RAILS_ENV=test`. Everything after `rspec` is passed through to RSpec.++```bash+spree rspec # full suite+spree rspec spec/models/product_spec.rb # one file+spree rspec spec/models/product_spec.rb:15 # one example+spree rspec --format documentation+```++Before the first run, create the test database with `spree rails db:test:prepare`.+### `spree user create`Create an admin user. Prompts interactively for email and password, or accepts flags for scripting.diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex c987d62993..4ff391b086 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -1,6 +1,6 @@{"name": "@spree/cli",- "version": "2.3.7",+ "version": "2.3.8","description": "CLI for managing Spree Commerce projects","type": "module","bin": {diff --git a/packages/cli/src/commands/rspec.ts b/packages/cli/src/commands/rspec.tsnew file mode 100644index 0000000000..ad16ee5152--- /dev/null+++ b/packages/cli/src/commands/rspec.ts@@ -0,0 +1,35 @@+import type { Command } from 'commander'+import { detectProject } from '../context.js'+import { dockerComposeExecOrRun } from '../docker.js'++// Run the RSpec suite inside the web container. Anything after `rspec` is+// forwarded verbatim — file paths, line numbers, and rspec flags all work.+// spree rspec+// spree rspec spec/models/spree/brand_spec.rb+// spree rspec spec/models/spree/brand_spec.rb:15+// spree rspec --format documentation+//+// RAILS_ENV=test is forced at the exec level: the dev image bakes+// RAILS_ENV=development, and while the starter's rails_helper re-forces test+// itself, setting it here keeps the command correct for apps whose helpers+// don't — and keeps every child process (spring, parallel workers) consistent.+// database.yml resolves the spree_test database from RAILS_ENV, so tests never+// touch the development data.+//+// When web is down we fall back to a one-off `compose run`, whose depends_on+// health-waits postgres — so tests run from a fully cold stack too.+export function registerRspecCommand(program: Command): void {+ program+ .command('rspec')+ .description('Run RSpec tests (`bundle exec rspec …`) inside the web container')+ .argument('[args...]', 'files, line numbers, and flags to pass to rspec')+ .allowUnknownOption(true)+ .passThroughOptions(true)+ .action(async (args: string[]) => {+ const ctx = detectProject()+ await dockerComposeExecOrRun(['bundle', 'exec', 'rspec', ...args], ctx.projectDir, {+ env: { RAILS_ENV: 'test' },+ edgeHint: 'then re-run spree rspec',+ })+ })+}diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex c5564310b6..762d3f3d36 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -20,6 +20,7 @@ import { registerRailsCommand } from './commands/rails.js'import { registerRakeCommand } from './commands/rake.js'import { registerRestartCommand } from './commands/restart.js'import { registerRoutesCommand } from './commands/routes.js'+import { registerRspecCommand } from './commands/rspec.js'import { registerSampleDataCommand } from './commands/sample-data.js'import { registerSeedCommand } from './commands/seed.js'import { registerStopCommand } from './commands/stop.js'@@ -33,7 +34,7 @@ const program = new Command().name('spree').description('CLI for managing Spree Commerce projects').version(VERSION)- // Required by passThroughOptions on subcommands (exec/rails/bundle/rake/task)+ // Required by passThroughOptions on subcommands (exec/rails/bundle/rake/task/rspec)// so flags like `ls -la` or `bin/rails routes -g foo` reach the inner command// instead of being parsed as options of the spree subcommand..enablePositionalOptions()@@ -80,6 +81,7 @@ registerRailsCommand(program)registerBundleCommand(program)registerRakeCommand(program)registerTaskCommand(program)+registerRspecCommand(program)registerConsoleCommand(program)// Spree-specific helpersdiff --git a/packages/cli/tests/rspec.test.ts b/packages/cli/tests/rspec.test.tsnew file mode 100644index 0000000000..82c8b621f7--- /dev/null+++ b/packages/cli/tests/rspec.test.ts@@ -0,0 +1,71 @@+import { Command } from 'commander'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { registerRspecCommand } from '../src/commands/rspec'+import { dockerComposeExecOrRun } from '../src/docker'++let projectDir: string++vi.mock('../src/context', () => ({+ detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),+}))++vi.mock('../src/docker', () => ({+ dockerComposeExecOrRun: vi.fn().mockResolvedValue(undefined),+}))++async function runRspec(args: string[] = []): Promise<void> {+ const program = new Command().enablePositionalOptions()+ registerRspecCommand(program)+ await program.parseAsync(['rspec', ...args], { from: 'user' })+}++describe('spree rspec', () => {+ beforeEach(() => {+ projectDir = '/proj'+ vi.clearAllMocks()+ })++ // Branching (exec vs one-off run vs monorepo-edge refusal) is covered by+ // dockerComposeExecOrRun's own tests in docker.test.ts; here we assert the+ // delegation shape: `bundle exec rspec` + forwarded args + RAILS_ENV=test.+ it('runs the full suite with RAILS_ENV=test when called bare', async () => {+ await runRspec()++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(['bundle', 'exec', 'rspec'], '/proj', {+ env: { RAILS_ENV: 'test' },+ edgeHint: 'then re-run spree rspec',+ })+ })++ it('forwards file paths and line numbers', async () => {+ await runRspec(['spec/models/spree/brand_spec.rb:15'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ ['bundle', 'exec', 'rspec', 'spec/models/spree/brand_spec.rb:15'],+ '/proj',+ expect.objectContaining({ env: { RAILS_ENV: 'test' } }),+ )+ })++ // Leading flags have no preceding positional, so they rely on+ // allowUnknownOption (passThroughOptions alone only covers flags after one).+ it('forwards leading rspec flags instead of parsing them', async () => {+ await runRspec(['--format', 'documentation'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ ['bundle', 'exec', 'rspec', '--format', 'documentation'],+ '/proj',+ expect.objectContaining({ env: { RAILS_ENV: 'test' } }),+ )+ })++ it('forwards flags following a path untouched', async () => {+ await runRspec(['spec/features/', '--fail-fast'])++ expect(dockerComposeExecOrRun).toHaveBeenCalledWith(+ ['bundle', 'exec', 'rspec', 'spec/features/', '--fail-fast'],+ '/proj',+ expect.objectContaining({ env: { RAILS_ENV: 'test' } }),+ )+ })+})