Allow for creating an Auditable model even if application is not spun up #962
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
As our team focuses on creating more testable components, we prefer unit tests over feature tests. Even better for those unit tests if they don't require the Laravel framework to be booted at all.
As is the case for most Laravel applications, Models are everywhere in our codebase. Sometimes we only want to test very limited things about a model behavior, or a function that takes in a model, but only needs a property or two from it. If we try to write a unit test (extending from
PHPUnit\Framework\TestCase
), we cannot even callnew User(['id' => 1])
because as Auditable boots, it attempts to access the App facade (which won't be set, and will raise an exception).For instance
Consider the following example
and a unit test
In the current version of Auditable, this will fail on the first line of the test with a RuntimeException.
The change implemented is to just swallow up this particular exception and not to attempt to add the observer.
Other approaches
Trigger a notice
Instead of swallowing the exception, we could
trigger_error()
, however, then there's a "notice" attached to the test.Leverage
Auditable::isAuditingDisabled()
I tried adding this check into
Auditable::isAuditingEnabled()
, but it broke tests, indicating a breaking change. Also, it's possible that a model is instantiated when auditing is temporarily disabled, but then when saving or changing the model later in the request, we do want auditing enabled.