pest icon indicating copy to clipboard operation
pest copied to clipboard

Shorthand expectation creation

Open markhuot opened this issue 3 years ago • 0 comments

Q A
Bug fix? no
New feature? yes
Fixed tickets none

This allows ->expect() to be called without any arguments. The benefit is you can chain ->expect() on to a HigherOrderCallable and use expectations without an inline closure. Take the following example where->factory(Model::class) is a method on my TestCase and returns a factory object that I can then call ->create() on.

it('supports posts without an author')
  ->factory(Post::class)
  ->create()->expect()
  ->title->not->toBeNull()
  ->author->toBeNull()

This allows you to write description less tests for objects that don't necessarily have assertion methods baked in. For complex creation processes it also avoids a layer of nesting. Take the following example where (in my opinion, the fn () => adds a layer of nesting that makes the whole block a little harder to read. You also have to find the extra ) to know where the ->expect() method ends and the assertions begin,

it('creates complex objects')
  ->expect(fn () => factory(Post::class)
    ->withAuthors()
    ->withCategories()
    ->create([
      'body' => 'The body of my post',
    ])
  )
  ->author->not->toBeNull()
  ->categories->not->toBeNull()
  ->body->toBe('The body of my post');

Compare that to the shorthand version where everything stays at the same outer level of nesting…

it('creates complex objects')
  ->factory(Post::class)
  ->withAuthors()
  ->withCategories()
  ->create([
    'body' => 'The body of my post',
  ])
  ->expect()
  ->author->not->toBeNull()
  ->categories->not->toBeNull()
  ->body->toBe('The body of my post');

markhuot avatar Sep 23 '22 20:09 markhuot