valeraefimov696's avatar

How to correctly write a unit test for controllers methords in laravel 5.5?

Please check the code I used to in my controller:

class ObjectsPagesController extends Controller
{
    public function store(Create $request)
    {

        $group = DeviceGroups::findOrFail($request->get('group_id'));
        $objectsPage = new ObjectsPages();
        $objectsPage->fill($request->all());
    $image = $request->file('image');
            $filename = uniqid('objects_pages') . '.' . $image->getClientOriginalExtension();
            \Storage::disk('uploads')->put("objects_pages/$filename", file_get_contents($image));
    $objectsPageRel->map_img = $filename;
        $objectsPage->save();
  return redirect()->route('objects.pages.index')->with('success', 'Done');
     }
      

}

On my request page, I wrote the codes below:

class Create extends FormRequest
{
    public function authorize()
    {
        return Auth::user()->can('add_objects_pages');
    }
    public function rules()
    {
        return [
            'group_id' => 'required|numeric',
            'header' => 'required|string|max:191',
            'link' => 'required|string|max:191|unique:objects_pages'
        ];
    }
}

I try the artisan command like below

php artisan make:test Pages --unit` But a clear instruction could not be found for laravel 5.5 what to do next?

my try

class Places extends TestCase
{
    use DatabaseTransactions; // Laravel will automatically roll back changes that happens in every test

    public function testExample()
    {
 $controller = new ObjectsPagesController();
        $Create = new Create();
        
         $request = $this->createMock(Create::class);
            $store = $controller->store($request);
         $this->expectsFormRequest(Index::class);
}
0 likes
3 replies
martinbean's avatar
Level 80

@valeraefimov696 Create a feature test, call your route, and then check the side-effects you were expecting happened:

class StoreObjectPageTest extends TestCase
{
    public function testStoreObjectIsCreated()
    {
        $this->actingAs($someUser)->post('/some/url');

        $this->assertDatabaseHas('store_objects', [
            // The attributes of a row you're expecting to see in DB
        ]);
    }
}
1 like

Please or to participate in this conversation.