It seems like you have two main questions here. Let's address each one separately.
- LazilyRefreshDatabase and ID sequencing:
When you use LazilyRefreshDatabase, it refreshes the database lazily, meaning it does not refresh the database before each test method. Instead, it starts a transaction before each test and rolls back after each test. This is why when you run a single test, you see the IDs starting from 1, because the database is fresh.
However, when you run all tests together, the IDs do not reset to 1 for each test because the database is not being dropped and recreated; it's just rolling back transactions. The auto-increment value for IDs in the database is not reset by a transaction rollback. This is why you see IDs starting from 4 or some other number after running multiple tests.
If you want to reset the IDs, you would need to refresh the database completely, which you can do by using RefreshDatabase instead of LazilyRefreshDatabase. However, this will slow down your tests because the database will be migrated for each test.
- Scope and test setup:
Regarding your scope and the test setup, it seems like you are trying to ensure that there is a State with id = 1 because your scope is looking for branches with state_id = 1. When you run all tests, the state with id = 1 might be created by a different test, and when you run the single test, it's not there, so you need to create it manually.
To ensure consistency, you can modify your test setup to always create a state with id = 1 before running your tests. You can do this by manually setting the ID when creating the state, assuming your database allows manual ID insertion:
State::truncate();
$newState = State::factory()->create(['id' => 1]);
Make sure that your database is set up to allow manual insertion of IDs, and be aware that this could interfere with other tests if they also expect to create a state with id = 1.
In summary, for consistent behavior across all tests, you may need to explicitly set up your database state before each test, and be aware of how the LazilyRefreshDatabase trait works with regard to database transactions and auto-incrementing IDs.