laravel-testing
Installation
SKILL.md
Laravel Testing
Every test reads the same way: a Pest test() named as a sentence, built from factories, run against a real database, with only its collaborators mocked and only the side effects it asserts faked. A unit test covers one class, built through the container; a feature test covers one controller's endpoints through HTTP. How to test each kind of class lives with the skill that owns it. This one owns the style they share, HTTP tests, models, builders and factories, fakes, and the test environment.
Rules
- Read the project's tests first.
tests/Pest.php,tests/TestCase.phpand a neighbouring test. Sign in, compare dates and build URLs with the helpers and expectations they define; this skill gives the shape, the project gives the helpers. test(), neverit(). Names are lowercase sentences: unit tests say what will happen ('will cancel a paid order','will not …'), HTTP tests what an actor can do ('can create an order','cannot …').- No
// Arrange,// Act,// Assertcomments. A blank line separates the setup, the call and the assertions. - Pest's Laravel functions, imported.
getJson(),mock(),freezeTime()andassertDatabaseHas()come fromuse function Pest\Laravel\…;, never$this->. - A failure is
->throws().test(...)->throws(OrderException::class, OrderException::cannotCancel()->getMessage())(laravel-exceptions).expect(fn () => …)->toThrow()only when the test asserts something after the throw, such as a rolled-back write. - Mock collaborators with
mock().Pest\Laravel\mock(X::class)binds the mock into the container, so the class under test, built withresolve(), receives it; there's nothing toswap().Mockery::mock()is only for an object the test hands over itself. laravel-actions has the recipe. - Real data, from factories. Models from
Order::factory()and its states, DTOs fromtestFactory()(laravel-dtos). Never mock a model or DTO, or build one from an inline array. Unit tests hit the database too: they create real rows and assert what was written. ->refresh()to re-read a model. It reloads the instance the test holds;fresh()returns a second copy and leaves the first stale.config([...])to change config, neverConfig::set().- Freeze what you assert.
freezeTime()before asserting a time,freezeSecond()when comparing with a stored timestamp (the database drops microseconds),travelTo()to move the clock.Str::freezeUlids()orStr::freezeUuids()before asserting a generated id. NeverCarbon::setTestNow(). - Fake only the events you assert.
Event::fake([OrderShipped::class]). A bareEvent::fake()swallows every event, model events included, so listeners the code depends on stop running and the test can't tell.