A
A
Alexander2018-12-11 18:35:51
PHPUnit
Alexander, 2018-12-11 18:35:51

How to properly test controller methods that interact with the database in Laravel?

Friends, hello everyone.
We were given the task of writing unit tests for controllers in Laravel.
Tests on assertStatus, assertViewHas - wrote.
Now we need to write tests for the rest of the controller methods, but there are questions, googling, I did not find exhaustive answers .. Help, please!
Here are some test methods:
1.

class BugsController extends Controller
{
    public function track(Request $request) {
        if(Bug::create([
            'title' => $request->data['title'],
            'note' => $request->data['note']
        ])) { return ['data' => 'Bug tracked']; }
        else { return ['data' => 'Something went wrong']; }
    }

If you test this method, it will write to the database. And if I don’t need it, do I need to wet it? (found info that some people use a test database, but this approach is also not suitable ..)
Could someone give an example of a test of this method plz?
2)
class AccountsController extends Controller
{     
public function status(Request $request)
    {
        $id = $request->input('account_id');
        $status = $request->input('status');
        $account = Account::where('id', $id)->first();

        if ($account->update(['user_status_id' => $status])) {
            \Session::flash('status', 'Status updated');
        } else {
            \Session::flash('error', 'Something went wrong');
        }

        return redirect()->route('accountlist');
    }
}

here, in principle, it’s clear: through this-> call () I turn to route, I pass post-data .. At the end, I’ll check for a redirect.
how to be with a DB again? I do not want to change any infa in the database.
Please direct me to the right path) Thank you in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rikcon, 2018-12-11
@Rikcon

And why the test DB does not approach?
It's just that when you run the tests, write a script that dumps the combat base (it's better, of course, to generate it through Faker)
into the test one and check there, change what you want.

A
Artyom, 2018-12-11
@dark1112

You could use the trait Illuminate\Foundation\Testing\DatabaseTransactions, it rolls back changes made to the database during the test.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question