Summer Sale! All accounts are 50% off this week.

panthro's avatar

Testing Models - Structure

I need to test some methods on my models. What is the advised setup here?

Do I just put my tests under Feature/Models/User and Feature/Models/Product for example?

0 likes
7 replies
tisuchi's avatar

@panthro

First of all, normally the model may be part of the unit/ test.

Do I just put my tests under Feature/Models/User and Feature/Models/Product for example?

Yes, it's also good practice to follow the class namespace to organize your unit test structure.

2 likes
panthro's avatar

@tisuchi I did not think I could use unit tests if interacting with a database?

1 like
tisuchi's avatar

@panthro It totally depends on your design.

But mostly feature represents either a full feature or end-to-end test.

(arguable) If you want to put model test in the feature I don't see any big issue here.

2 likes
automica's avatar

Feature tests are usually for methods invoked by the router, and would represent interactions with controllers and their responses.

Unit tests would be for testing smaller units of work, so a class with a public handle method which interacts with private methods only in that class.

It's perfectly fine to use DB calls within unit tests. You might use a factory to create a user and have a unit test, testing a method in that class that does something with the data.

Whilst you could test a model in a Feature name space, a single class shouldnt be a feature.

TBH though, the most important thing is that you actually write tests and you have test coverage. How you organise them is less important than them existing.

2 likes
panthro's avatar

@automica thanks for the advice.

When I move it to a unit test I can't seem to do things like: $this->actingAs($user);

What should I do?

1 like
automica's avatar

@panthro you shouldnt be testing authentication within a Unit test. Acting as User implies a login and that would be a Feature.

1 like

Please or to participate in this conversation.