I have the following test:
public function testExample()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user,'api')->json('POST', 'api/rangos?api_token='.$user->api_token,
[
"denominacion"=>"Visitante",
"nivel"=>"1"
]
);
$response->assertStatus(201);
$response->assertJsonStructure([
"id",
"denominacion",
"nivel",
"miembros",
"updated_at",
"created_at"
]);
}
The function I'm unit testing is as follows:
public function store(Request $request){
$data=new Rango($request->all());
$data->save();
return response()->json($data->load("miembros"),201);
}
The unit test passes successfully, the problem is that when executing the test the data is stored in the database. ie if I run the test 10 times the data is logged 10 times and I want to prevent that from happening.
How do I get it to pass the test without the data being permanently recorded in the database?
Edition
I already tried to do it with the trait RefreshDatabase
and what happens with RefreshDatabase is that it deletes any other data inside my database, that is, it cleans the entire database, and I don't want that either.
What happens is that the method
create()
, in addition to creating an instance of the model, inserts the data into the database, what you are looking for is the methodmake()
, which only creates models but does not save them in the database.Edit:
If you necessarily have to insert data in BD. Then you should use
RefreshDatabase
laravel's Trait, specified here . Which does aroll-back
to the database after each test.Edit:
Another solution is to work with
transacciones
when doing a test, Laravel provides the methodssetUp()
andtearDown()
, therefore, it can be handled like this:These methods must be inside your test class.
you could also use DatabaseTransactions , its use would be the following: