The wonderful thing about Laravel is that, if there’s something specific you need to accomplish, then there’s…Laracasts
Tandem Shower
https://theawesomer.com/photos/2022/04/tandem_shower_t.jpg
Like to share a shower with your sweetheart but hate fighting for warm water? Boona’s cleverly-designed dual shower head attaches to your existing water source and holds in place with a tension rod, distributing water evenly from both ends of your shower. Each head is adjustable for people of different heights.
The Awesomer
Comic for April 17, 2022
https://assets.amuniversal.com/23121b60863e013a9e10005056a9545d
Top Dilbert Searches
marketing,
project,
cloud,
catbert,
leadership,
budget,
birthday,
engineer,
time sheet,
sales,
wally,
strategy,
dogbert,
powerpoint,
project management,
topper,
leader,
boss,
change,
meeting,
data,
management,
mordac
Dilbert Daily Strip
Access Patterns for MySQL
Access patterns intrigue me because it seems that everyone knows what they are and talks about them, but there’s also very little written about them—in MySQL literature, at least.
That’s why I set out to enumerate a list of access patterns (specific to MySQL).
Since there’s no apparent standard for access patterns, I cannot say how my list measures up, but after spending most my career with MySQL, I know this: it is necessary to consider these access patterns when evaluating and improving MySQL performance.
Simply put: you cannot ignore how the application accesses MySQL.
Planet MySQL
A Video Ode to the Nylon Climbing Rope
https://s3.amazonaws.com/images.gearjunkie.com/uploads/2016/09/beckey-gear-laid-out-200×133.jpg
How are climbing ropes made? What can they do? (Answer: incredible things.) How do they do it? GearJunkie digs in, video essay style.
As climbers, we routinely stake our lives on a few nylon fibers and seldom give it a thought beyond that.
Did you know that the machines that make climbing ropes use up to 48 different spools of material at once? What about that each meter of an Edelrid rope passes through human hands before it leaves the factory floor?
We didn’t know either, to be honest. We were always more wrapped up in what we (and especially other, bolder adventurers) could do with them.
Read on for an expository ode to climbing ropes, made possible by the Edelrid factory team and buoyed by cameos from the sport’s best.
But first, a whipper compilation.
(Skip to about 40 seconds in to watch GearJunkie correspondent Christian Black rip gear out of Indian Creek’s infamous “Fingers in a Light Socket” while riding a 40-foot fall.)
Natural Fear: Early Plant-Based Ropes
In the early days, “climbing ropes” were basically boat ropes. Braided cords of plant-based material were the norm.
Hemp was a common fiber choice, and climbers relied on hemp ropes as late as the 1950s. The plant is suitably robust (in tensile strength), but it’s cumbersome compared to modern rope materials and doesn’t stretch much. Its resistance to stretching limits its strength.
Almost all available evidence indicates risk tolerance was very different back in the day. Helmy and Fred Beckey’s second ascent of the South Face of Mt. Waddington (still a serious route today) in 1942 would undoubtedly have utilized hemp ropes.
Antique Gear List: Climbers In 1942 Were Tougher Than Nails
Royal Robbins probably used hemp ropes on the first 5.9 in America, “Open Book,” in 1952. Climbers had first aided the route using wooden chocks (yes, 2x4s) the year before.
Robbins didn’t take any falls on the route, but similar ropes and gear held falls. Ignore the wannabe Ken Burns narration in this clip and hang with it for the first 20 seconds to watch a bonafide boat rope whipper.
Nylon Ropes Change the Game
In 1935, DuPont patented nylon, or synthetic polyamide, and changed the climbing world forever. The new fiber was mega-strong, stretchy, and lightweight — perfect for protecting climbers on the sharp end.
Nylon can exhibit different properties depending on its weave pattern. Some weaves, for instance, can make it pliable and stretchy; others can result in a durable, abrasion-resistant material.
World’s First Recycled Climbing Rope: Edelrid Reveals ‘NEO 3R’
That dual applicability led to the “kernmantel” structure, which defines the market today. Edelrid introduced the idea in 1953. The company is German, and in that language, “kern” means core, and “mantel” means sheath.
Simply put, a kernmantel rope’s core gives it stretch and strength. The sheath protects the core from the elements. Both parts consist of nylon fibers.
Nylon climbing ropes can let humans do unfathomable things. The late Dan Osman arguably pushed climbing ropes closer to their limit than any other human before or since. Tragically, he also broke the limit dying while jumping on a single rope.
Osman’s specialties included free-soloing and the world’s biggest rope swings. Skip to 3 minutes to watch the “Sky Pilot” rope jump 1,000 feet off Yosemite’s Leaning Tower.
“Holy sphincter” is right, Dan-O.
How Climbing Rope is Made
GearJunkie found messaging with Edelrid’s rope manufacturing team similar to talking to any group of genius technicians: informative and often prohibitively technical.
In paraphrase, here’s how it all goes down.
Step One: Nylon to Filaments to Twisted Yarn
The first step in rope making is turning nylon into thin filaments. It’s melted, extruded, and then pulled out into strands. The strands combine to form nylon yarn, the primary material for any climbing rope.
Edelrid can achieve different rope characteristics by twisting the yarn together in up to five layers. It can also weave in materials like aramid and polyester to affect the rope’s elasticity.
To avoid curling and kinking, the manufacturer twists half the yarn to the left and half to the right. Edelrid’s technicians twist each nylon filament profusely — a meter-long segment contains between 100 and 140 twists.
After the twisting process, the yarn is ready for shrinking.
Step Two: Shrinkage
Properly shrunk yarn is integral to a rope’s dynamic qualities. Shrinking reduces its strength slightly, giving it the critical ability to stretch and rebound. Static ropes are made with unshrunk yarn.
Edelrid Head of Product Phillippe Westenberger said shrinking is critical in making a dynamic rope.
“Shrinking is the key process to give a rope its dynamic characteristics and make it a dynamic climbing rope. During this process, pressure, heat, and humidity shrink the fibers so that they can elongate later on again, for example, to catch a fall,” Westenberger explained.
“But not all shrinkage is the same, of course. Different materials and different intended rope characteristics demand different shrinking processes. Basically, performance then depends on the total time and how differently the three parameters are ramped up and down.”
Elongation and rebound are the main ingredients to a lead rope’s field performance. To visualize why, watch Sonnie Trotter take repeated 50-foot whippers off a classic Scottish trad route — apparently, all on the same cord.
To shrink the yarn, Edelrid weaves it into loose sheets and puts it into an industrial autoclave — essentially, a heavy-duty chemical reaction sauna.
Each raw fiber shrinks to about two-thirds of its original size and thickness.
Step Three: Braiding a Climbing Rope
After shrinking, Edelrid de-weaves the loose sheets and spins the sheath yarn onto bobbins. The bobbins sit aside until they’re ready to go into the braiding machine. The core yarn, meanwhile, gets its water-repellent treatment at this stage.
After that, the main event kicks off. Braiding machines work in a precise choreography: up to 48 bobbins can circulate, spin, and revolve around a single machine to make one rope. The bobbins mount on the machine’s “carriers.” Each one can carry a different yarn, and together, they spin the core and the sheath at the same time.
The general rule for sheath braiding is this: more carriers and thinner yarn make for the best rope characteristics. A rope’s sheath percentage increases with the number of carriers on the machine that braided it.
Intuitively, sheath percentage refers to how much of the rope is the sheath, measured by weight. Using thinner sheath yarn helps keep the rope’s weight down, and its surface slick.
“Generally, we can see a certain correlation of the higher the sheath percentage and the slicker the surface, the longer the rope will last,” said Westenberger.
He explained the utility in terms of handling and toughness. “Slickness of a rope decreases friction, so one can see the logical consequence of abrasion resistance. It also reduces rope drag when climbing and handling in belay devices.”
Trango Agility 9.8 Review: The Rope Most Climbers Need Most of the Time
Like every parameter of rope construction, Edelrid controls the braiding process tightly. They set the speed the machine pulls the rope through itself, and they set the angle the machines braid the yarn and the tension of each thread.
The size of the hole machine pulls the rope through is the final variable and probably the most relatable to the everyday climber. It determines, of course, the rope’s diameter.
Step Four: Practicality
Edelrid makes about 1,000 m of a given rope during a production run.
Once it has a fully braided rope, it runs it through one of its various dry treatments. Most are PFC-based, but Eco Dry treatment uses paraffin, a type of wax.
Believe it or not, each meter of every Edelrid rope then passes through human hands before it leaves the factory floor. Experts feel for stiff spots or any other irregularities resulting from braiding.
Custom(ish) Fit: Hestra’s Carefully Crafted Belay Glove Review
Then another machine cuts the rope to length and stamps the middle mark. Workers finish the marks to make sure they’re distinct, and then manually melt and tape the ends. A final machine coils it for packaging.
Internal strength and break testing take place before Edelrid sends any rope to the International Climbing and Mountaineering Federation (UIAA) for certification.
How Strong Is Climbing Rope, Really?
The UIAA assumes a lot of responsibility (ethics and litigation) as the international certifying body for rope safety metrics. Consumers, by and large, purchase a lot of UIAA-rated climbing ropes around the world every day. Then, almost categorically, they go out into the world and abuse them.
All that considered, the organization generally plays it safe. Most field testing finds strength ratings reliable, and the “UIAA falls” ratings are thought to be conservative.
For entertaining, nonpretentious rope break testing that leverages professional lab technology, check out this clip from Hard is Easy. As a bonus, watch MC Ben rip an anchor out of his ceiling (in a somewhat improvised test from earlier days) about a minute in.
The team addresses plenty of field-applicable situations many climbers will be familiar with. “Should I cut the rope if I can squeeze a loop flat between my fingers? Should I worry about this fuzz?” And so on.
Tendon Ropes Factory Tour With … Wait, Who?
Curious to watch the whole modern rope-making process, one step at a time? Tour Tendon’s Bolatice, Czech Republic, facility with none other than “Tendon Top Employee Václav Nečesaný.”
Nečesaný knows what he’s talking about. And the results are in hand. If you take the video’s word for it, his ropes have helped world-class climbers pull off 5.15a/9a+ first ascents.
Rope Solo Rock Climbing: Understanding How It’s Done
The post A Video Ode to the Nylon Climbing Rope appeared first on GearJunkie.
GearJunkie
Free Unreal Engine game creation tool ‘Core’ is coming to macOS, iOS
https://photos5.appleinsider.com/gallery/47934-93637-Core-xl.jpg
“Core,” a free game creation tool based on Unreal Engine and available so far only on PC, is coming to macOS and iOS in the summer of 2022.
Manticore Games, the developer of Core, announced the expansion on Friday, which asked the game creation app’s one-year anniversary. When it arrives on iPhone, iPad, and Mac, Core gamers will be able to cross-play with Windows players.
Additionally, the company said that developers who want to get a head start in creating mobile experiences using Core will be able to begin working with a new suite of iOS optimization tools starting Friday.
Thus far, the Core platform has only been available on Windows PCs through the Epic Games Store. Core itself is a free-to-play game with a built-in game creation system. As of Friday, Manticore Games says there are more than 50,000 “games, worlds, and events” that players can check out.
Other apps that are similar to Core are also making moves to expand to other platforms. Meta’s Horizon Worlds, so far an Oculus exclusive, is said to be expanding to mobile and web in the future. Roblox, which has long been available on a variety of platforms, may soon arrive on PlayStation, too.
AppleInsider News
Learn how to start Testing in Laravel with Simple Examples using PHPUnit and PEST
https://laravelnews.imgix.net/images/pest-php-dark.png?ixlib=php-3.3.1
When talking about automated tests or unit tests in any programming language, there are two groups of people:
- Those who don’t write automated tests and think they’re a waste of time
- Those who do write tests and then can’t imagine their work without them
So, with this article, I will try to convince the former camp to look at the other side and see the benefits, and see how easy it is to start with automated testing in Laravel.
First, let’s talk about the “why” and then I’ll show a few very basic examples of the “how”.
Why You Need Automated Tests
Automated tests are not complicated: they just run parts of your code for you and report any errors. That’s the most simple way to describe them. Imagine that you’re launching a new feature in your app, and then a personal robot assistant would go and manually test the new functionality for you, also testing if the new code didn’t break anything from the old features.
That’s the main benefit: re-testing all the features automatically. And it may seem like extra work, but if you don’t tell that “robot” to do it, then you should do it manually yourself, right? Or do you just launch the new features without too much testing, hoping that the users would report the bugs? I call that method sarcastically “fingers-crossed-driven development”.
With every new feature of your app, automated tests pay off more and more.
- Feature 1: saves X minutes of testing manually
- Feature 2: saves 2X minutes – for feature 2 and feature 1 again
- Feature 3: saves 3X minutes…
- etc.
You get the idea. Imagine your application in a year or two, with new developers on the team who wouldn’t even know how that “Feature 1” works or how to reproduce it for testing. So, your future self will thank you massively for writing the automated tests.
Of course, if you think that your project is a very short-term one and you don’t care that much about its future… Nah, I believe in your good intentions, so let me show you how it’s easy to start testing.
Our First Automated Tests
To run the first automated test in Laravel, you don’t need to write any code. Yup, you’ve read that right. Everything is already configured and prepared in the default Laravel installation, including the first real basic example.
You can try to install a Laravel project and immediately run the first tests:
1laravel new project
2cd project
3php artisan test
This should be the result in your console:
1 PASS Tests\Unit\ExampleTest
2✓ that true is true
3
4 PASS Tests\Feature\ExampleTest
5✓ the application returns a successful response
6
7Tests: 2 passed
8Time: 0.10s
If we take a look at the default Laravel /tests
folder, we have two files.
tests/Feature/ExampleTest.php:
1class ExampleTest extends TestCase
2{
3 public function test_the_application_returns_a_successful_response()
4 {
5 $response = $this->get('/');
6
7 $response->assertStatus(200);
8 }
9}
There’s no need to know any syntax, to understand what is happening here: loading the homepage and checking if the HTTP status code is “200 OK”.
Also notice how the method name test_the_application_returns_a_successful_response()
becomes readable text when viewing the test results, just replacing the underscore symbol with a space.
tests/Unit/ExampleTest.php:
1class ExampleTest extends TestCase
2{
3 public function test_that_true_is_true()
4 {
5 $this->assertTrue(true);
6 }
7}
This looks a bit pointless, checking that true is true? We’ll talk about unit tests specifically, a bit later. For now, you need to understand what is generally happening in every test.
- Each test file in the
tests/
folder is a PHP Class extending the TestCase of PHPUnit - Inside of each class, you may create multiple methods, usually one method for one situation to be tested
- Inside of each method, there are three actions: preparation of the situation, then action, and then checking (asserting) if the result is as expected
Structurally, that’s all you need to know, everything else depends on the exact things you want to test.
To generate an empty test class, you just run this command:
1php artisan make:test HomepageTest
It would generate the file tests/Feature/HomepageTest.php
:
1class HomepageTest extends TestCase
2{
3 // Replace this method with your own ones
4 public function test_example()
5 {
6 $response = $this->get('/');
7
8 $response->assertStatus(200);
9 }
10}
What If Tests Fail?
Let me show you what happens if the test assertions don’t return the expected result.
Let’s edit the example tests to this:
1class ExampleTest extends TestCase
2{
3 public function test_the_application_returns_a_successful_response()
4 {
5 $response = $this->get('/non-existing-url');
6
7 $response->assertStatus(200);
8 }
9}
10
11
12class ExampleTest extends TestCase
13{
14 public function test_that_true_is_false()
15 {
16 $this->assertTrue(false);
17 }
18}
And now, if we run php artisan test
again:
1
2 FAIL Tests\Unit\ExampleTest
3⨯ that true is true
4
5 FAIL Tests\Feature\ExampleTest
6⨯ the application returns a successful response
7
8---
9
10• Tests\Unit\ExampleTest > that true is true
11Failed asserting that false is true.
12
13at tests/Unit/ExampleTest.php:16
14 12▕ * @return void
15 13▕ */
16 14▕ public function test_that_true_is_true()
17 15▕ {
18➜ 16▕ $this->assertTrue(false);
19 17▕ }
20 18▕ }
21 19▕
22
23• Tests\Feature\ExampleTest > the application returns a successful response
24Expected response status code [200] but received 404.
25Failed asserting that 200 is identical to 404.
26
27at tests/Feature/ExampleTest.php:19
28 15▕ public function test_the_application_returns_a_successful_response()
29 16▕ {
30 17▕ $response = $this->get('/non-existing-url');
31 18▕
32➜ 19▕ $response->assertStatus(200);
33 20▕ }
34 21▕ }
35 22▕
36
37
38Tests: 2 failed
39Time: 0.11s
As you can see, there are two statements marked as FAIL, with explanations below and arrows to the exact test line that failed the assertion. So this is how the errors are shown. Convenient, isn’t it?
Simple Real-Life Example: Registration Form
Let’s get more practical and look at a real-life example. Imagine that you have a form, and you need to test various cases: check if it fails if filled with invalid data, check if it succeeds with the correct input, etc.
Did you know that the official Laravel Breeze starter kit comes with the feature tests inside? So, let’s take a look at a few examples from there:
tests/Feature/RegistrationTest.php
1use App\Providers\RouteServiceProvider;
2use Illuminate\Foundation\Testing\RefreshDatabase;
3use Tests\TestCase;
4
5class RegistrationTest extends TestCase
6{
7 use RefreshDatabase;
8
9 public function test_registration_screen_can_be_rendered()
10 {
11 $response = $this->get('/register');
12
13 $response->assertStatus(200);
14 }
15
16 public function test_new_users_can_register()
17 {
18 $response = $this->post('/register', [
19 'name' => 'Test User',
20 'email' => 'test@example.com',
21 'password' => 'password',
22 'password_confirmation' => 'password',
23 ]);
24
25 $this->assertAuthenticated();
26 $response->assertRedirect(RouteServiceProvider::HOME);
27 }
28}
Here we have two tests in one class, as they are both related to the registration form: one is checking if the form is loaded correctly, and another one checks if the submission works well.
We get familiar with two other methods of checking the result, two more assertions: $this->assertAuthenticated()
and $response->assertRedirect()
. You can check all the available assertions in the official documentation of PHPUnit and Laravel Response. Keep in mind that some general assertions happen on $this
object, while others check the specific $response
from the route call.
Another important thing is the use RefreshDatabase;
statement, with the trait, included above the class. It is needed when your test actions may affect the database, like in this example, registration adds a new entry in the users
database table. For that, you would need to create a separate testing database that would be refreshed with php artisan migrate:fresh
, every time the tests are executed.
You have two options: physically create a separate database, or use an in-memory SQLite database. It is both configured in the file phpunit.xml
that comes by default with Laravel. Specifically, you need this part:
1<php>
2 <env name="APP_ENV" value="testing"/>
3 <env name="BCRYPT_ROUNDS" value="4"/>
4 <env name="CACHE_DRIVER" value="array"/>
5 <!-- <env name="DB_CONNECTION" value="sqlite"/> -->
6 <!-- <env name="DB_DATABASE" value=":memory:"/> -->
7 <env name="MAIL_MAILER" value="array"/>
8 <env name="QUEUE_CONNECTION" value="sync"/>
9 <env name="SESSION_DRIVER" value="array"/>
10 <env name="TELESCOPE_ENABLED" value="false"/>
11</php>
See the DB_CONNECTION
and DB_DATABASE
which are commented out? If you have SQLite on your server, the easiest action is to just uncomment those lines, and your tests will run on that in-memory database.
In this test, we assert that the user is authenticated successfully and is redirected to the correct homepage, but we can also test the actual data in the database.
In addition to this code:
1$this->assertAuthenticated();
2$response->assertRedirect(RouteServiceProvider::HOME);
We can also use Database Testing assertions and do something like this:
1$this->assertDatabaseCount('users', 1);
2
3// Or...
4$this->assertDatabaseHas('users', [
5 'email' => 'test@example.com',
6]);
Another Real-Life Example: Login Form
Let’s take a look at one more test from Laravel Breeze.
tests/Feature/AuthenticationTest.php:
1class AuthenticationTest extends TestCase
2{
3 use RefreshDatabase;
4
5 public function test_login_screen_can_be_rendered()
6 {
7 $response = $this->get('/login');
8
9 $response->assertStatus(200);
10 }
11
12 public function test_users_can_authenticate_using_the_login_screen()
13 {
14 $user = User::factory()->create();
15
16 $response = $this->post('/login', [
17 'email' => $user->email,
18 'password' => 'password',
19 ]);
20
21 $this->assertAuthenticated();
22 $response->assertRedirect(RouteServiceProvider::HOME);
23 }
24
25 public function test_users_can_not_authenticate_with_invalid_password()
26 {
27 $user = User::factory()->create();
28
29 $this->post('/login', [
30 'email' => $user->email,
31 'password' => 'wrong-password',
32 ]);
33
34 $this->assertGuest();
35 }
36}
This is about the login form. The logic is similar to the registration, right? But three methods instead of two, so this is an example of testing both good and bad scenarios. So, the common logic is that you should test both cases: when things go well and when they fail.
Also, what you see in this test is the usage of Database Factories: Laravel creates a fake user (again, on your refreshed testing database) and then tries to log in, with correct or incorrect credentials.
Again, Laravel generates the default factory with fake data for the User
model, out of the box.
database/factories/UserFactory.php:
1class UserFactory extends Factory
2{
3 public function definition()
4 {
5 return [
6 'name' => $this->faker->name(),
7 'email' => $this->faker->unique()->safeEmail(),
8 'email_verified_at' => now(),
9 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
10 'remember_token' => Str::random(10),
11 ];
12 }
13}
See, how many things are prepared by Laravel itself, so it would be easy for us to start testing?
So, if we run php artisan test
after installing Laravel Breeze, we should see something like this:
1 PASS Tests\Unit\ExampleTest
2✓ that true is true
3
4 PASS Tests\Feature\Auth\AuthenticationTest
5✓ login screen can be rendered
6✓ users can authenticate using the login screen
7✓ users can not authenticate with invalid password
8
9 PASS Tests\Feature\Auth\EmailVerificationTest
10✓ email verification screen can be rendered
11✓ email can be verified
12✓ email is not verified with invalid hash
13
14 PASS Tests\Feature\Auth\PasswordConfirmationTest
15✓ confirm password screen can be rendered
16✓ password can be confirmed
17✓ password is not confirmed with invalid password
18
19 PASS Tests\Feature\Auth\PasswordResetTest
20✓ reset password link screen can be rendered
21✓ reset password link can be requested
22✓ reset password screen can be rendered
23✓ password can be reset with valid token
24
25 PASS Tests\Feature\Auth\RegistrationTest
26✓ registration screen can be rendered
27✓ new users can register
28
29 PASS Tests\Feature\ExampleTest
30✓ the application returns a successful response
31
32Tests: 17 passed
33Time: 0.61s
Feature Tests VS Unit Tests VS Others
You’ve seen the tests/Feature
and tests/Unit
subfolders. What is the difference between them? The answer is a little “philosophical”.
Globally, outside of Laravel/PHP ecosystem, there are different kinds of automated tests. You can find such terms as:
- Unit tests
- Feature tests
- Integration tests
- Functional tests
- End-to-end tests
- Acceptance tests
- Smoke tests
- etc.
It sounds complicated, and the actual differences between those test types sometimes are blurred. That’s why Laravel simplified all those confusing terms and grouped them into two: unit/feature.
In simple words, feature tests try to run the actual features of your applications: get the URL, call the API, mimic the exact behavior like filling in the form. Feature tests usually execute the same or similar thing as any project user would do, manually, in real life.
Unit tests have two meanings. Generally, you may find that any automated tests are called “unit tests”, and the whole process may be called “unit testing”. But in the context of feature vs unit, this process is about testing a specific non-public unit of your code, in isolation. For example, you have some Laravel class with a method that calculates something, like the total price of the order with parameters. So, your unit test would assert if the correct results are returned by that method (unit of code), with different parameters.
To generate a unit test, you need to add a flag:
1php artisan make:test OrderPriceTest --unit
The generated code is the same as the default unit test from Laravel:
1class OrderPriceTest extends TestCase
2{
3 public function test_example()
4 {
5 $this->assertTrue(true);
6 }
7}
As you can see, there’s no RefreshDatabase
, and that’s one of the most common definitions of a unit test: it doesn’t touch the database, it works like a “black box”, in isolation from the running application.
Trying to mimic the example I mentioned earlier, let’s imagine we have a service class OrderPrice
.
app/Services/OrderPriceService.php:
1class OrderPriceService
2{
3 public function calculatePrice($productId, $quantity, $tax = 0.0)
4 {
5 // Some kind of calculation logic
6 }
7}
Then, the unit test could look something like this:
1class OrderPriceTest extends TestCase
2{
3 public function test_single_product_no_taxes()
4 {
5 $product = Product::factory()->create(); // generate a fake product
6 $price = (new OrderPriceService())->calculatePrice($product->id, 1);
7 $this->assertEquals(1, $price);
8 }
9
10 public function test_single_product_with_taxes()
11 {
12 $price = (new OrderPriceService())->calculatePrice($product->id, 1, 20);
13 $this->assertEquals(1.2, $price);
14 }
15
16 // More cases with more parameters
17}
In my personal experience with Laravel projects, the absolute majority of the tests are Feature tests, not Unit tests. First, you need to test if your application works, the way how real people would use it.
Next, if you have special calculations or logic that you can define as a unit, with parameters, you may create unit tests specifically for that.
Sometimes, writing tests requires changing the code itself, and refactoring it to be more “testable”: separating the units into special classes or methods.
When/How To Run Tests?
What is the actual usage of that php artisan test
, when you should run that?
There are different approaches, depending on your company workflow, but typically, you need to make sure that all tests are “green” (meaning, no errors) before you push your latest code changes to the repository.
So, you work locally on your task, and when you feel like you’ve finished, you run tests to make sure you didn’t break anything. Remember, your code may cause bugs not only in your logic but also unintentionally break some other behavior in someone else’s code written a long time ago.
If we take it a step further, it’s possible to automate a lot of things. With various CI/CD tools, you can specify your tests to be executed whenever someone pushes the changes to a specific Git branch, or before merging the code into the production branch. The easiest workflow would be to use Github Actions, I have a separate video demonstrating it.
What Should You Test?
There are various opinions on how big your so-called “test coverage” should be: should you test every operation and every possible case on every page, or just limit your work to the most important parts.
Indeed, this is where I agree with people blaming automated testing for taking more time than bringing the actual benefits. That may happen if you write tests for every single detail. That said, it may be required by your project: the main question is “what is the price of the potential error”.
In other words, you need to prioritize your testing efforts with the question “What would happen if this code fails?” If your payment system has bugs, it will directly impact the business. Then, if your roles/permissions functionality is broken, then it’s a huge security issue.
I like how Matt Stauffer phrased it during one conference: “You need to test those things first, which, if they fail, would get you fired from your job”. Of course, it’s an exaggeration, but you get the idea: test the important things first. And then other functionality, if you have time for it.
PEST: New Popular Alternative to PHPUnit
All the examples above are based on the default Laravel testing tool: PHPUnit. But over the years other tools were appearing in the ecosystem, and one of the latest popular ones is PEST. Created by the official Laravel employee Nuno Maduro, it has the goal of simplifying the syntax, making it even quicker to write the code for tests.
Under the hood, it runs on top of PHPUnit, as an additional layer, just trying to minimize some default repeating parts of PHPUnit code.
Let’s take a look at an example. Remember the default Feature test class in Laravel? I will remind you:
1namespace Tests\Feature;
2
3use Illuminate\Foundation\Testing\RefreshDatabase;
4use Tests\TestCase;
5
6class ExampleTest extends TestCase
7{
8 public function test_the_application_returns_a_successful_response()
9 {
10 $response = $this->get('/');
11
12 $response->assertStatus(200);
13 }
14}
Do you know how the same test would look with PEST?
1test('the application returns a successful response')->get('/')->assertStatus(200);
Yes, ONE line of code, and that’s it. So, the goal of PEST is to remove the overhead of:
- Creating classes and methods for everything;
- Extending TestCase;
- Putting actions on separate lines – in PEST, you can chain them.
To generate a PEST test in Laravel, you need to specify an additional flag:
1php artisan make:test HomepageTest --pest
At the time of writing this article, PEST is quite popular among Laravel developers, but it’s your personal preference whether to use this extra tool and learn its syntax, in addition to a well-known PHPUnit.
So, that’s all you need to know about the basics of automated testing. From here, it’s your choice on what tests to create and how to run them in your projects.
For more information, refer to the official Laravel docs on testing.
Laravel News
This parody of a Twitter employee responding to Elon Musk’s takeover of Twitter is absolutely spot-on 🤣
https://media.notthebee.com/articles/625878b58d968625878b58d96a.jpg
"Elon Musk is making my job at Twitter unsafe!!!"
Not the Bee
This 1970s-Style Star Trek: The Next Generation Animated Series Is Beyond Perfect
https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/5b73b02a781ab7951e857532eb3f2f0a.jpg
There are few perfect things in this world, so it’s worth celebrating them when we find them. Case in point: this unbelievably outstanding video from Gazelle Automations, which imagines if the classic animation studio Filmation had managed to get its hands on the Star Trek: The Next Generation crew.
Trek fans likely know that Filmation did the original Star Trek: The Animated Series from 1973, while others may recognize the name as the maker of the classic He-Man and the Masters of the Universe cartoon of the ‘80s. But anyone who’s ever laid eyes on a Filmation cartoon knows the studio was incredibly cheap. It reused as much footage as possible, it animated as little as possible, and it slowed down the story as much as possible, all to spend as little as possible. So when you watch this video, be assured it’s not a parody, but an exact replica of what Filmation would have done with The Next Generation had the studio made a spin-off back in the ‘70s:
The attention to detail is astounding, from the lack of the whites of their eyes, to the strange angles of the shots, to the way each Borg has to be teleported in succession. I swear, when Worf raises his phaser to shoot the Borg, that’s even the same (low) number of cels Filmation used for the motion. Here, compare the clip to this scene from the classic Trek cartoon:
Uncanny, right? What really gets me is that Gazelle Automations even nailed the characters’ shifting eyes, which represented the sum total of emotional reactions the Filmation characters would have in response to… well, anything, basically. Even the purple, oversimplified designs of the Borg are perfect. No notes!
Wondering where our RSS feed went? You can pick the new up one here.
Gizmodo
How to Adjust and Zero In Your Rifle’s Iron Sights for Improved Accuracy
https://cdn.athlonoutdoors.com/wp-content/uploads/sites/6/2021/06/Mepro-FRBS.jpg
Although optics are all the rage now, many still like the simplicity and dependability of good old iron sights. They make a great backup as well. However, if the front and rear sights are not properly aligned your shot placement and overall accuracy will suffer. Not to mention, if they are really far off, they may pose more of a risk in a home or self-defense scenario. This short primer provides the basics on how to adjust your iron sights if they need it.

RELATED STORY
Mepro FRBS: Backup Flip-Up Sights Add Hyper-Bright Illumination
A Primer on How to Adjust and Zero In Iron Sights
Although some people like to zero at 25 meters, others prefer to zero at 50 yards. However, you may want to zero at 100 yards depending on your intended use. But keep in mind the effect this will have on close-quarters application. For this exercise, we chose a 50-yard zero.
Zeroing In
1.) Be sure you and your rifle are on a stable surface such as a bench rest or sandbags. Any movement, no matter how slight, will throw off your shots and affect the point of bullet impact.
2.) Place a target 25 yards downrange and fire a three-round group.
3.) Based on where your shots hit, determine if you need to adjust for windage, elevation, or both.
4.) If you need to adjust for elevation, first, figure out which sight to move. If it is the front sight, move the post up or down (a tool may be required). A general rule for adjusting a front sight is to move the sight in the opposite direction you want your group to move. For example, if you are shooting low, lower the front sight. However, your front sight may not be adjustable, in which case use your rear sight to adjust for elevation.

5.) If you need to adjust for windage, move the rear sight windage knob (left/right). However, you may also need to adjust the rear sight for elevation, and you will use the elevation dial for this (up/down). The general rule for adjusting a rear iron sight is to move it in the direction you want your group to move. For example, if you’re hitting the target high and to the right, move your sight down and to the left. The FORS (Front Sight Opposite, Rear Sight Same) acronym should help remember.

6.) Shoot three-round groups and adjust the sights until the desired point-of-aim, point-of-impact is achieved.
7.) Once you have a zero at 25 yards, back the target back to 50 yards and repeat. At this point, you should only need to adjust the elevation.
Things to Consider
There are some things to take into consideration when adjusting iron sights. First, if you are not able to shoot a tight group, make sure you are using a proper bench rest. Likewise, make sure your bench rest is stable.
If you are unable to achieve a tight group due to inexperience, it may be best to have a gunsmith perform your sight adjustments. Once the adjustments are made, make sure to practice regularly until you are able to tighten your group.
Next, if you are having a hard time dialing in your zero, try adjusting the elevation or windage separately. For example, shoot a three-round group and then adjust your elevation. Then, shoot another three-round group and adjust your windage. Focusing on one adjustment at a time may help to simplify things.
Finally, if you’re sights are really far off and you are not hitting paper at all, pull the target closer. Bring the target in to 10 yards and get a zero at that distance. Then, move it out to 25 yards. And finally, out to the intended 50 yards.
Once you’re done adjusting and zeroing in your sights, you are ready for the range, the hunt, or personal defense.
The post How to Adjust and Zero In Your Rifle’s Iron Sights for Improved Accuracy appeared first on Personal Defense World.
Personal Defense World