Using Laravel Pest, Generate the following well-structured Laravel Pest Test Cases. Use inline comments where the logic might not be immediately clear.
PHPDoc should be comprehensive, detailing parameters, return types, and exceptions thrown. Adhere to Laravel and Filament PHP best practices, including naming conventions, code organization.
Unit Test (Use Cases and Edge Cases)
code
Role Model:
Use Cases:
Creating a Role with valid name and unique slug.
Updating a Role's name and slug.
Soft deleting a Role and verifying deleted_at is set.
Restoring a soft-deleted Role.
Attaching and detaching Users to/from a Role.
Edge Cases:
Attempting to create a Role with a duplicate slug.
Updating a Role with an invalid slug format.
Deleting a Role that has associated Users.
User Model:
Use Cases:
Creating a User with valid data, including name, unique email, and hashed password.
Updating User details and changing roles.
Soft deleting and restoring a User.
Associating and dissociating Roles, Posts, and Comments.
Edge Cases:
Creating a User with an email that already exists.
Updating a User's password with non-matching confirmation.
Deleting a User who has Posts or Comments.
Category Model:
Use Cases:
Creating a Category with a unique slug.
Updating Category details.
Soft deleting and restoring a Category.
Associating Posts with a Category.
Edge Cases:
Creating a Category with a duplicate slug.
Deleting a Category that has associated Posts.
Tag Model:
Use Cases:
Creating a Tag with a unique slug.
Updating Tag details.
Soft deleting and restoring a Tag.
Associating Posts with a Tag.
Edge Cases:
Creating a Tag with a duplicate slug.
Deleting a Tag that is associated with multiple Posts.
Post Model:
Use Cases:
Creating a Post with valid data, including title, unique slug, and status.
Updating Post details and changing status.
Soft deleting and restoring a Post.
Associating Tags, Comments, and Likes with a Post.
Edge Cases:
Creating a Post with a duplicate slug.
Publishing a Post without setting published_at.
Deleting a Post that has Comments and Likes.
Comment Model:
Use Cases:
Creating a Comment with valid data, including content and status.
Updating Comment details and changing status.
Soft deleting and restoring a Comment.
Associating a parent Comment for nested comments.
Edge Cases:
Creating a Comment with a non-existent parent ID.
Deleting a Comment that has child Comments.
Analytics Model:
Use Cases:
Creating Analytics records with valid views_count, likes_count, and comments_count.
Updating Analytics counts.
Associating Analytics with a Post.
Edge Cases:
Creating Analytics for a non-existent Post.
Setting negative values for counts.
Below are comprehensive Laravel Pest test cases for the provided modules. Each model has dedicated tests covering both use cases and edge cases. The tests include detailed PHPDoc comments and inline comments to ensure clarity and maintainability. The tests adhere to Laravel and Filament PHP best practices, including proper naming conventions and organized code structure.
Role Model Tests
php
<?php
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
/**
* @group RoleModel
*/
uses(RefreshDatabase::class);
beforeEach(function () {
// Set up any necessary preconditions here
});
/**
* Test creating a Role with valid name and unique slug.
*/
it('can create a role with valid name and unique slug', function () {
$role = Role::create([
'name' => 'Administrator',
'slug' => 'administrator',
]);
expect($role->id)->toBeInt()
->and($role->name)->toBe('Administrator')
->and($role->slug)->toBe('administrator')
->and($role->deleted_at)->toBeNull();
});
/**
* Test updating a Role's name and slug.
*/
it('can update a role\'s name and slug', function () {
$role = Role::create([
'name' => 'Editor',
'slug' => 'editor',
]);
$role->update([
'name' => 'Content Editor',
'slug' => 'content-editor',
]);
expect($role->name)->toBe('Content Editor')
->and($role->slug)->toBe('content-editor');
});
/**
* Test soft deleting a Role and verifying deleted_at is set.
*/
it('can soft delete a role and sets deleted_at', function () {
$role = Role::create([
'name' => 'Subscriber',
'slug' => 'subscriber',
]);
$role->delete();
expect($role->deleted_at)->not()->toBeNull()
->and(Role::withTrashed()->find($role->id))->not()->toBeNull();
});
/**
* Test restoring a soft-deleted Role.
*/
it('can restore a soft-deleted role', function () {
$role = Role::create([
'name' => 'Contributor',
'slug' => 'contributor',
]);
$role->delete();
$role->restore();
expect($role->deleted_at)->toBeNull()
->and(Role::find($role->id))->not()->toBeNull();
});
/**
* Test attaching and detaching Users to/from a Role.
*/
it('can attach and detach users to/from a role', function () {
$role = Role::create([
'name' => 'Manager',
'slug' => 'manager',
]);
$user1 = User::factory()->create();
$user2 = User::factory()->create();
// Attach users
$role->users()->attach([$user1->id, $user2->id]);
expect($role->users()->count())->toBe(2);
// Detach one user
$role->users()->detach($user1->id);
expect($role->users()->count())->toBe(1)
->and($role->users->first()->id)->toBe($user2->id);
});
/**
* Test attempting to create a Role with a duplicate slug.
*/
it('throws an exception when creating a role with a duplicate slug', function () {
Role::create([
'name' => 'Editor',
'slug' => 'editor',
]);
$this->expectException(QueryException::class);
Role::create([
'name' => 'Another Editor',
'slug' => 'editor', // Duplicate slug
]);
});
/**
* Test updating a Role with an invalid slug format.
*/
it('throws a validation exception when updating a role with an invalid slug format', function () {
$role = Role::create([
'name' => 'Author',
'slug' => 'author',
]);
// Define invalid slug (e.g., contains spaces)
$invalidSlug = 'invalid slug';
// Assuming there's a validation rule in the controller or model,
// but since we're testing the model directly, we'll simulate validation.
$validator = Validator::make(
['slug' => $invalidSlug],
['slug' => 'required|unique:roles,slug|alpha_dash']
);
expect($validator->fails())->toBeTrue()
->and($validator->errors()->has('slug'))->toBeTrue();
});
/**
* Test deleting a Role that has associated Users.
*/
it('can delete a role that has associated users', function () {
$role = Role::create([
'name' => 'Tester',
'slug' => 'tester',
]);
$user = User::factory()->create();
$role->users()->attach($user->id);
// Delete the role
$role->delete();
// Ensure the relationship is soft deleted
expect(Role::withTrashed()->find($role->id))->not()->toBeNull()
->and($user->roles()->withTrashed()->where('role_id', $role->id)->exists())->toBeFalse();
});
User Model Tests
php
Category Model Tests
php
Tag Model Tests
php
<?php
use App\Models\Tag;
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Database\QueryException;
/**
* @group TagModel
*/
uses(RefreshDatabase::class);
beforeEach(function () {
// Set up any necessary preconditions here
});
/**
* Test creating a Tag with a unique slug.
*/
it('can create a tag with a unique slug', function () {
$tag = Tag::create([
'name' => 'Laravel',
'slug' => 'laravel',
]);
expect($tag->id)->toBeInt()
->and($tag->slug)->toBe('laravel')
->and($tag->deleted_at)->toBeNull();
});
/**
* Test updating Tag details.
*/
it('can update tag details', function () {
$tag = Tag::create([
'name' => 'PHP',
'slug' => 'php',
]);
$tag->update([
'name' => 'PHP Programming',
'slug' => 'php-programming',
]);
expect($tag->name)->toBe('PHP Programming')
->and($tag->slug)->toBe('php-programming');
});
/**
* Test soft deleting and restoring a Tag.
*/
it('can soft delete and restore a tag', function () {
$tag = Tag::create([
'name' => 'JavaScript',
'slug' => 'javascript',
]);
$tag->delete();
expect($tag->deleted_at)->not()->toBeNull()
->and(Tag::withTrashed()->find($tag->id))->not()->toBeNull();
$tag->restore();
expect($tag->deleted_at)->toBeNull()
->and(Tag::find($tag->id))->not()->toBeNull();
});
/**
* Test associating Posts with a Tag.
*/
it('can associate posts with a tag', function () {
$tag = Tag::create([
'name' => 'Vue.js',
'slug' => 'vue-js',
]);
$post1 = Post::factory()->create();
$post2 = Post::factory()->create();
$tag->posts()->attach([$post1->id, $post2->id]);
expect($tag->posts()->count())->toBe(2);
});
/**
* Test creating a Tag with a duplicate slug.
*/
it('throws an exception when creating a tag with a duplicate slug', function () {
Tag::create([
'name' => 'React',
'slug' => 'react',
]);
$this->expectException(QueryException::class);
Tag::create([
'name' => 'Another React',
'slug' => 'react', // Duplicate slug
]);
});
/**
* Test deleting a Tag that is associated with multiple Posts.
*/
it('can delete a tag that is associated with multiple posts', function () {
$tag = Tag::create([
'name' => 'Tailwind CSS',
'slug' => 'tailwind-css',
]);
$post1 = Post::factory()->create();
$post2 = Post::factory()->create();
$tag->posts()->attach([$post1->id, $post2->id]);
// Delete the tag
$tag->delete();
// Ensure the tag is soft deleted
expect($tag->deleted_at)->not()->toBeNull();
// Ensure the relationship is handled correctly
// Posts should still exist but not be associated with the deleted tag
expect($post1->tags()->withTrashed()->count())->toBe(0)
->and($post2->tags()->withTrashed()->count())->toBe(0);
});
Post Model Tests
php
Comment Model Tests
php
Analytics Model Tests
php
Notes:
Factories: The tests assume that model factories (User::factory(), Post::factory(), etc.) are properly defined. If they are not, you'll need to create them accordingly.
Validation Rules: Some tests simulate validation by directly using Laravel's Validator facade. In a real-world scenario, validation is typically handled in request classes or controllers. Adjust these tests based on how validation is implemented in your application.
Cascade Deletes: The behavior when deleting parent models (e.g., Role, Category) that have associated child models (e.g., User, Posts) depends on your database's foreign key constraints and any onDelete rules defined in your migrations. Ensure that your tests align with the actual behavior of your application.
Likes Association: The tests for the Post model mention likes but assume they are handled via a separate relationship or table. You'll need to implement appropriate tests based on how likes are structured in your application.
Exception Handling: The tests expect certain operations to throw QueryException when database constraints are violated. Depending on your application's error handling, you might need to catch different exceptions or assert error messages.
Soft Deletes: The tests utilize Laravel’s SoftDeletes trait. Ensure that all models that require soft deleting include this trait.
These tests provide a solid foundation for ensuring the integrity and reliability of your application's core modules. Adjust and extend them as necessary to fit the specific requirements and business logic of your project.
Not yet included in a published release.
<?php
use App\Models\User;
use App\Models\Role;
use App\Models\Post;
use App\Models\Comment;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
/**
* @group UserModel
*/
uses(RefreshDatabase::class);
beforeEach(function () {
// Set up any necessary preconditions here
});
/**
* Test creating a User with valid data, including name, unique email, and hashed password.
*/
it('can create a user with valid data', function () {
$user = User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => Hash::make('password123'),
]);
expect($user->id)->toBeInt()
->and($user->name)->toBe('John Doe')
->and($user->email)->toBe('john@example.com')
->and(Hash::check('password123', $user->password))->toBeTrue()
->and($user->deleted_at)->toBeNull();
});
/**
* Test updating User details and changing roles.
*/
it('can update user details and change roles', function () {
$user = User::factory()->create([
'name' => 'Jane Smith',
'email' => 'jane@example.com',
]);
$role1 = Role::create(['name' => 'User', 'slug' => 'user']);
$role2 = Role::create(['name' => 'Admin', 'slug' => 'admin']);
// Attach initial role
$user->roles()->attach($role1->id);
// Update user details
$user->update([
'name' => 'Jane Doe',
'email' => 'jane.doe@example.com',
]);
// Change roles
$user->roles()->detach($role1->id);
$user->roles()->attach($role2->id);
expect($user->name)->toBe('Jane Doe')
->and($user->email)->toBe('jane.doe@example.com')
->and($user->roles()->count())->toBe(1)
->and($user->roles->first()->slug)->toBe('admin');
});
/**
* Test soft deleting and restoring a User.
*/
it('can soft delete and restore a user', function () {
$user = User::factory()->create();
$user->delete();
expect($user->deleted_at)->not()->toBeNull()
->and(User::withTrashed()->find($user->id))->not()->toBeNull();
$user->restore();
expect($user->deleted_at)->toBeNull()
->and(User::find($user->id))->not()->toBeNull();
});
/**
* Test associating and dissociating Roles, Posts, and Comments.
*/
it('can associate and dissociate roles, posts, and comments', function () {
$user = User::factory()->create();
$role = Role::create(['name' => 'Editor', 'slug' => 'editor']);
$post = Post::factory()->create(['user_id' => $user->id]);
$comment = Comment::factory()->create(['user_id' => $user->id]);
// Associate role
$user->roles()->attach($role->id);
expect($user->roles()->count())->toBe(1);
// Dissociate role
$user->roles()->detach($role->id);
expect($user->roles()->count())->toBe(0);
// Verify posts and comments association
expect($user->posts()->count())->toBe(1)
->and($user->comments()->count())->toBe(1);
// Delete post and comment
$post->delete();
$comment->delete();
expect($user->posts()->withTrashed()->count())->toBe(1)
->and($user->comments()->withTrashed()->count())->toBe(1);
});
/**
* Test creating a User with an email that already exists.
*/
it('throws an exception when creating a user with a duplicate email', function () {
User::factory()->create([
'email' => 'duplicate@example.com',
]);
$this->expectException(QueryException::class);
User::factory()->create([
'email' => 'duplicate@example.com', // Duplicate email
]);
});
/**
* Test updating a User's password with non-matching confirmation.
*/
it('throws a validation exception when updating password with non-matching confirmation', function () {
$user = User::factory()->create();
$newPassword = 'newpassword123';
$passwordConfirmation = 'differentpassword';
// Simulate password update with confirmation
$data = [
'password' => $newPassword,
'password_confirmation' => $passwordConfirmation,
];
$validator = Validator::make($data, [
'password' => 'required|string|min:8|confirmed',
]);
expect($validator->fails())->toBeTrue()
->and($validator->errors()->has('password'))->toBeTrue();
});
/**
* Test deleting a User who has Posts or Comments.
*/
it('can delete a user who has posts or comments', function () {
$user = User::factory()->create();
$post = Post::factory()->create(['user_id' => $user->id]);
$comment = Comment::factory()->create(['user_id' => $user->id]);
// Delete the user
$user->delete();
// Ensure the user is soft deleted
expect($user->deleted_at)->not()->toBeNull();
// Check if posts and comments are also soft deleted or handle accordingly
// Depending on the cascade settings, adjust expectations
expect(Post::withTrashed()->find($post->id))->not()->toBeNull()
->and(Comment::withTrashed()->find($comment->id))->not()->toBeNull();
});
<?php
use App\Models\Category;
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Database\QueryException;
/**
* @group CategoryModel
*/
uses(RefreshDatabase::class);
beforeEach(function () {
// Set up any necessary preconditions here
});
/**
* Test creating a Category with a unique slug.
*/
it('can create a category with a unique slug', function () {
$category = Category::create([
'name' => 'Technology',
'slug' => 'technology',
'description' => 'All about tech.',
]);
expect($category->id)->toBeInt()
->and($category->slug)->toBe('technology')
->and($category->deleted_at)->toBeNull();
});
/**
* Test updating Category details.
*/
it('can update category details', function () {
$category = Category::create([
'name' => 'Health',
'slug' => 'health',
]);
$category->update([
'name' => 'Health & Wellness',
'slug' => 'health-wellness',
'description' => 'Health related topics.',
]);
expect($category->name)->toBe('Health & Wellness')
->and($category->slug)->toBe('health-wellness')
->and($category->description)->toBe('Health related topics.');
});
/**
* Test soft deleting and restoring a Category.
*/
it('can soft delete and restore a category', function () {
$category = Category::create([
'name' => 'Finance',
'slug' => 'finance',
]);
$category->delete();
expect($category->deleted_at)->not()->toBeNull()
->and(Category::withTrashed()->find($category->id))->not()->toBeNull();
$category->restore();
expect($category->deleted_at)->toBeNull()
->and(Category::find($category->id))->not()->toBeNull();
});
/**
* Test associating Posts with a Category.
*/
it('can associate posts with a category', function () {
$category = Category::create([
'name' => 'Travel',
'slug' => 'travel',
]);
$post1 = Post::factory()->create(['category_id' => $category->id]);
$post2 = Post::factory()->create(['category_id' => $category->id]);
expect($category->posts()->count())->toBe(2);
});
/**
* Test creating a Category with a duplicate slug.
*/
it('throws an exception when creating a category with a duplicate slug', function () {
Category::create([
'name' => 'Lifestyle',
'slug' => 'lifestyle',
]);
$this->expectException(QueryException::class);
Category::create([
'name' => 'Another Lifestyle',
'slug' => 'lifestyle', // Duplicate slug
]);
});
/**
* Test deleting a Category that has associated Posts.
*/
it('can delete a category that has associated posts', function () {
$category = Category::create([
'name' => 'Education',
'slug' => 'education',
]);
$post = Post::factory()->create(['category_id' => $category->id]);
// Delete the category
$category->delete();
// Ensure the category is soft deleted
expect($category->deleted_at)->not()->toBeNull();
// Depending on cascade settings, posts might be soft deleted or remain
// Adjust the expectation accordingly. Here, we assume posts remain.
expect(Post::find($post->id))->not()->toBeNull()
->and($post->category_id)->toBe($category->id);
});
<?php
use App\Models\Post;
use App\Models\User;
use App\Models\Category;
use App\Models\Tag;
use App\Models\Comment;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
/**
* @group PostModel
*/
uses(RefreshDatabase::class);
beforeEach(function () {
// Set up necessary preconditions
});
/**
* Test creating a Post with valid data, including title, unique slug, and status.
*/
it('can create a post with valid data', function () {
$user = User::factory()->create();
$category = Category::create(['name' => 'Tech', 'slug' => 'tech']);
$post = Post::create([
'user_id' => $user->id,
'category_id' => $category->id,
'title' => 'Introduction to Laravel',
'slug' => 'introduction-to-laravel',
'content' => 'Laravel is a web application framework...',
'status' => 'draft',
]);
expect($post->id)->toBeInt()
->and($post->title)->toBe('Introduction to Laravel')
->and($post->slug)->toBe('introduction-to-laravel')
->and($post->status)->toBe('draft')
->and($post->deleted_at)->toBeNull();
});
/**
* Test updating Post details and changing status.
*/
it('can update post details and change status', function () {
$user = User::factory()->create();
$category = Category::create(['name' => 'Health', 'slug' => 'health']);
$post = Post::create([
'user_id' => $user->id,
'category_id' => $category->id,
'title' => 'Health Benefits of Yoga',
'slug' => 'health-benefits-of-yoga',
'content' => 'Yoga improves flexibility...',
'status' => 'draft',
]);
$post->update([
'title' => 'Advanced Health Benefits of Yoga',
'status' => 'published',
'published_at' => now(),
]);
expect($post->title)->toBe('Advanced Health Benefits of Yoga')
->and($post->status)->toBe('published')
->and($post->published_at)->not()->toBeNull();
});
/**
* Test soft deleting and restoring a Post.
*/
it('can soft delete and restore a post', function () {
$post = Post::factory()->create();
$post->delete();
expect($post->deleted_at)->not()->toBeNull()
->and(Post::withTrashed()->find($post->id))->not()->toBeNull();
$post->restore();
expect($post->deleted_at)->toBeNull()
->and(Post::find($post->id))->not()->toBeNull();
});
/**
* Test associating Tags, Comments, and Likes with a Post.
*/
it('can associate tags, comments, and likes with a post', function () {
$post = Post::factory()->create();
$tags = Tag::factory()->count(3)->create();
$comments = Comment::factory()->count(2)->create(['post_id' => $post->id]);
// Attach tags
$post->tags()->attach($tags->pluck('id'));
// Assume likes are handled via a separate relationship or table
// For simplicity, we'll skip likes association here
expect($post->tags()->count())->toBe(3)
->and($post->comments()->count())->toBe(2);
});
/**
* Test creating a Post with a duplicate slug.
*/
it('throws an exception when creating a post with a duplicate slug', function () {
$user = User::factory()->create();
$category = Category::create(['name' => 'Science', 'slug' => 'science']);
Post::create([
'user_id' => $user->id,
'category_id' => $category->id,
'title' => 'Quantum Physics Basics',
'slug' => 'quantum-physics-basics',
'content' => 'Quantum physics is...',
'status' => 'draft',
]);
$this->expectException(QueryException::class);
Post::create([
'user_id' => $user->id,
'category_id' => $category->id,
'title' => 'Advanced Quantum Physics',
'slug' => 'quantum-physics-basics', // Duplicate slug
'content' => 'Advanced topics in quantum physics...',
'status' => 'draft',
]);
});
/**
* Test publishing a Post without setting published_at.
*/
it('throws a validation exception when publishing a post without setting published_at', function () {
$user = User::factory()->create();
$category = Category::create(['name' => 'Art', 'slug' => 'art']);
$post = Post::create([
'user_id' => $user->id,
'category_id' => $category->id,
'title' => 'Impressionist Paintings',
'slug' => 'impressionist-paintings',
'content' => 'Impressionism is a 19th-century art movement...',
'status' => 'draft',
]);
// Attempt to update status to 'published' without setting published_at
$data = [
'status' => 'published',
];
$validator = Validator::make($data, [
'status' => 'required|in:draft,published,archived',
'published_at' => 'required_if:status,published|date',
]);
expect($validator->fails())->toBeTrue()
->and($validator->errors()->has('published_at'))->toBeTrue();
});
/**
* Test deleting a Post that has Comments and Likes.
*/
it('can delete a post that has comments and likes', function () {
$post = Post::factory()->create();
$comments = Comment::factory()->count(3)->create(['post_id' => $post->id]);
// Assuming Likes are handled via a separate relationship or table
// For simplicity, we'll skip likes association here
$post->delete();
expect($post->deleted_at)->not()->toBeNull()
->and(Post::withTrashed()->find($post->id))->not()->toBeNull()
->and(Comment::withTrashed()->where('post_id', $post->id)->count())->toBe(3);
});
<?php
use App\Models\Comment;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
/**
* @group CommentModel
*/
uses(RefreshDatabase::class);
beforeEach(function () {
// Set up necessary preconditions
});
/**
* Test creating a Comment with valid data, including content and status.
*/
it('can create a comment with valid data', function () {
$user = User::factory()->create();
$post = Post::factory()->create();
$comment = Comment::create([
'user_id' => $user->id,
'post_id' => $post->id,
'content' => 'Great post!',
'status' => 'approved',
]);
expect($comment->id)->toBeInt()
->and($comment->content)->toBe('Great post!')
->and($comment->status)->toBe('approved')
->and($comment->deleted_at)->toBeNull();
});
/**
* Test updating Comment details and changing status.
*/
it('can update comment details and change status', function () {
$comment = Comment::factory()->create([
'status' => 'pending',
]);
$comment->update([
'content' => 'Updated comment content.',
'status' => 'approved',
]);
expect($comment->content)->toBe('Updated comment content.')
->and($comment->status)->toBe('approved');
});
/**
* Test soft deleting and restoring a Comment.
*/
it('can soft delete and restore a comment', function () {
$comment = Comment::factory()->create();
$comment->delete();
expect($comment->deleted_at)->not()->toBeNull()
->and(Comment::withTrashed()->find($comment->id))->not()->toBeNull();
$comment->restore();
expect($comment->deleted_at)->toBeNull()
->and(Comment::find($comment->id))->not()->toBeNull();
});
/**
* Test associating a parent Comment for nested comments.
*/
it('can associate a parent comment for nested comments', function () {
$parentComment = Comment::factory()->create();
$childComment = Comment::create([
'user_id' => $parentComment->user_id,
'post_id' => $parentComment->post_id,
'content' => 'This is a reply.',
'status' => 'approved',
'parent_id' => $parentComment->id,
]);
expect($childComment->parent_id)->toBe($parentComment->id)
->and($parentComment->comments()->count())->toBe(1)
->and($parentComment->comments->first()->id)->toBe($childComment->id);
});
/**
* Test creating a Comment with a non-existent parent ID.
*/
it('throws an exception when creating a comment with a non-existent parent ID', function () {
$user = User::factory()->create();
$post = Post::factory()->create();
$this->expectException(QueryException::class);
Comment::create([
'user_id' => $user->id,
'post_id' => $post->id,
'content' => 'Invalid parent comment.',
'status' => 'pending',
'parent_id' => 9999, // Non-existent parent ID
]);
});
/**
* Test deleting a Comment that has child Comments.
*/
it('can delete a comment that has child comments', function () {
$parentComment = Comment::factory()->create();
$childComment = Comment::create([
'user_id' => $parentComment->user_id,
'post_id' => $parentComment->post_id,
'content' => 'Child comment.',
'status' => 'approved',
'parent_id' => $parentComment->id,
]);
// Delete parent comment
$parentComment->delete();
// Ensure parent is soft deleted
expect($parentComment->deleted_at)->not()->toBeNull()
->and(Comment::withTrashed()->find($parentComment->id))->not()->toBeNull();
// Child comment should remain unaffected unless cascading is set
expect(Comment::find($childComment->id))->not()->toBeNull()
->and($childComment->parent_id)->toBe($parentComment->id);
});
<?php
use App\Models\Analytics;
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Database\QueryException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
/**
* @group AnalyticsModel
*/
uses(RefreshDatabase::class);
beforeEach(function () {
// Set up necessary preconditions
});
/**
* Test creating Analytics records with valid views_count, likes_count, and comments_count.
*/
it('can create analytics records with valid counts', function () {
$post = Post::factory()->create();
$analytics = Analytics::create([
'post_id' => $post->id,
'views_count' => 100,
'likes_count' => 25,
'comments_count' => 10,
]);
expect($analytics->id)->toBeInt()
->and($analytics->views_count)->toBe(100)
->and($analytics->likes_count)->toBe(25)
->and($analytics->comments_count)->toBe(10)
->and($analytics->deleted_at)->toBeNull();
});
/**
* Test updating Analytics counts.
*/
it('can update analytics counts', function () {
$analytics = Analytics::factory()->create([
'views_count' => 50,
'likes_count' => 10,
'comments_count' => 5,
]);
$analytics->update([
'views_count' => 150,
'likes_count' => 30,
'comments_count' => 15,
]);
expect($analytics->views_count)->toBe(150)
->and($analytics->likes_count)->toBe(30)
->and($analytics->comments_count)->toBe(15);
});
/**
* Test associating Analytics with a Post.
*/
it('can associate analytics with a post', function () {
$post = Post::factory()->create();
$analytics = Analytics::create([
'post_id' => $post->id,
'views_count' => 200,
'likes_count' => 50,
'comments_count' => 20,
]);
expect($analytics->post()->exists())->toBeTrue()
->and($analytics->post->id)->toBe($post->id);
});
/**
* Test creating Analytics for a non-existent Post.
*/
it('throws an exception when creating analytics for a non-existent post', function () {
$this->expectException(QueryException::class);
Analytics::create([
'post_id' => 9999, // Non-existent post ID
'views_count' => 100,
'likes_count' => 20,
'comments_count' => 5,
]);
});
/**
* Test setting negative values for counts.
*/
it('throws a validation exception when setting negative values for counts', function () {
$post = Post::factory()->create();
// Attempt to create analytics with negative counts
$data = [
'post_id' => $post->id,
'views_count' => -100,
'likes_count' => -20,
'comments_count' => -5,
];
$validator = Validator::make($data, [
'post_id' => 'required|exists:posts,id',
'views_count' => 'required|integer|min:0',
'likes_count' => 'required|integer|min:0',
'comments_count' => 'required|integer|min:0',
]);
expect($validator->fails())->toBeTrue()
->and($validator->errors()->has('views_count'))->toBeTrue()
->and($validator->errors()->has('likes_count'))->toBeTrue()
->and($validator->errors()->has('comments_count'))->toBeTrue();
});