Search code examples
phplaravellaravel-8laravel-testing

Laravel8 tdd: session is missing expected key errors


I just want to test an easy input field but I get this error!

enter image description here

/** @test */
public function email_must_be_a_valid_email()
 {
   $response = $this->post('/api/contacts', array_merge($this->data(), ['email' => 'NOT AN EMAIL']));
   $response->assertSessionHasErrors('email');
 }


private function data()
{
  return [
          'name' => 'Test Name',
          'email' => '[email protected]',
          'birthday' => '05/14/1988',
          'company' => 'ABC String'
        ];
}

Thses are the Controller and the request rule. I hope u can help me with it.

class StoreController extends Controller
{
    public function store(ContactsRequest $request)
    {
        $data = $request->validated();
        Contact::create($data);
    }
}

public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required|email',
            'birthday' => 'required',
            'company' => 'required',
        ];
    }

I hope u can help me with it.


Solution

  • Thanks for your tips. I've solved the problem! But this kind of error message does not help at all to find the solution quickly. The solution is that I need to be logged in to create contact and then validate form data. But the error message says something completely different!

    protected $user;
    
    protected function setUp(): void
    {
       parent::setUp();
       $this->user = User::factory()->create();
       $this->user->createToken(Str::random(30))->plainTextToken;
    }
    
    
    /** @test */
    public function email_must_be_a_valid_email()
    {
       $this->actingAs($this->user);
       $response = $this->post('/api/contacts', array_merge($this->data(), ['email' => 'NOT AN EMAIL']));
       $response->assertSessionHasErrors('email');
    }
    

    enter image description here