Setting attributes for models during testing

I am trying to test a controller and mocking the models. Everything seems to be going well until the view is loaded, since it cannot get the properties of that view to be loaded through the relationship.

I tried to set these properties by using andSet()

object, but then it gives me an error getAttribute() does not exist on this mocked object.

,

Here is my controller method.

public function __construct(ApplicationRepositoryInterface $application)
{
    $this->beforeFilter('consumer_application');

    $this->application = $application;
}

public function edit($application_id)
{
    $application = $this->application->find($application_id);

    $is_consumer = Auth::user()->isAdmin() ? 'false' : 'true';

    return View::make('application.edit')
        ->with('application', $application)
        ->with('is_consumer', $is_consumer)
        ->with('consumer', $application->consumer);
}

      

And my test ...

public function setUp()
{
    parent::setUp();
    $this->mock = Mockery::mock($this->app->make('ApplicationRepositoryInterface'));
}

public function testEdit()
{
    $this->app->instance('ApplicationRepositoryInterface', $this->mock);

    $this->mock
        ->shouldReceive('find')
        ->once()
        ->andReturn(Mockery::mock('Application'))
        ->andSet('consumer', Mockery::mock('Consumer'));

    Auth::shouldReceive('user')
        ->once()
        ->andReturn(Mockery::mock(array('isAdmin' => 'true')));

    $application_id = Application::first()->id;
    $this->call('GET', 'consumer/application/'.$application_id.'/edit');

    $this->assertResponseOk();
    $this->assertViewHas('application');
    $this->assertViewHas('is_consumer');
    $this->assertViewHas('consumer');
}

      

The most I got is removing the part andSet()

that takes care of that getAttribute() does not exist on this mock object

but then it tells me it consumer

is undefined when the view is loaded and still not working.

+3


source to share


1 answer


You must change:

 Auth::shouldReceive('user')
    ->once()
    ->andReturn(Mockery::mock(array('isAdmin' => 'true')));

      



For this:

 Auth::shouldReceive('user->isAdmin')
    ->once()
    ->andReturn('true');

      

+2


source







All Articles