php - how to mock model->save()?
I need to mock a db model that calls the function save().
Test
//Setup function
$this->jobAccessor = Mockery::mock(JobAccessor::class);
$this->job = Mockery::mock(Job::class);
$this->app->instance('App\Models\Job', $this->job);
$this->app->instance('App\Data\JobAccessor', $this->jobAccessor);
//testing function
$job = new Job([
'id' => 22,
'user_id' => 123
]);
$this->jobAccessor->shouldReceive('find')
->with($jobId)
->andReturns($job);
$this->job->shouldReceive('save')->once();
function to test
$job = $this->jobAccessor->find($this->id);
//do stuff with job then save
$job->save(); //how do I mock save here?
How can i mock $job->save();
the way i done above doesnt work. I get the following errors Illuminate\Database\QueryException: could not find driver
. It's trying to access the database still.
Answer
Solution:
Not sure, but I think you need to declare the save method as :
$this->job->shouldReceive('save')->with(m::on(function ($job) use ($data) {
// set all attributes of your job Model
return
$job->id == $data['id']
&& $job->name == $data['name'];
// ....
}))
->andReturns($this->job)
->once();
Source