Relationship returns empty in tests

Posted 1 week ago by Danieloplata

Hi guys,

I'm trying to test a route in one of my projects, which has a bit of middleware that checks the user's country. My test is failing because the relationship is returning an empty array.

Panel.php

public function countries()
{
    return $this->belongsToMany(Country::class);
}

PanelRedirectTest.php

use RefreshDatabase;

    public function setUp(): void
    {
        parent::setup();
        $this->be($user = factory('App\User')->create());
        $this->project = factory('App\Project')->create();
        $this->panel = factory('App\Panel')->create(['project_id' => $this->project->id]);

        $this->countryPanel = factory('App\CountryPanel')->create([
            'panel_id' => $this->panel->id,
            'country_id' => 231
        ]);
    }


    /** @test */
    public function a_respondent_from_a_whitelisted_country_can_access_the_start_route()
    {
        $this->withoutExceptionHandling();
        
        dd($this->countryPanel); // Correctly returns a record with panel_id = 1 and country_id = 231

        $respondentID ='testRespondent';

        $this->get(route('redirectStart', [
            'panelid' => $this->panel->id,
            'respondentid' => $respondentID
        ]))->assertRedirect($this->panel->redirectLink . $respondentID);
    }

Test fail:

Failed asserting that two strings are equal.
Expected :'https://example.org/survey/testRespondent'
Actual   :'https://example.org/error/country'

I've been trying to figure out the issue, DD'ing every step and it seems to fall apart because the relationship returns empty when called during the test. What's confusing for me is that DD'ing this while manually testing the routes, I get all the correct responses. The actual route is working when using the software, I just can't get my test to return green.

Please sign in or create an account to participate in this conversation.