72 - Extracting a Finder Method

This commit is contained in:
Adam Wathan
2017-02-10 18:53:09 -05:00
parent 8ac3ab3441
commit 27fa6d98e2
3 changed files with 31 additions and 1 deletions

View File

@@ -9,7 +9,7 @@ class OrdersController extends Controller
{
public function show($confirmationNumber)
{
$order = Order::where('confirmation_number', $confirmationNumber)->first();
$order = Order::findByConfirmationNumber($confirmationNumber);
return view('orders.show', ['order' => $order]);
}
}

View File

@@ -22,6 +22,11 @@ class Order extends Model
return $order;
}
public static function findByConfirmationNumber($confirmationNumber)
{
return self::where('confirmation_number', $confirmationNumber)->firstOrFail();
}
public function concert()
{
return $this->belongsTo(Concert::class);

View File

@@ -7,6 +7,7 @@ use App\Reservation;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class OrderTest extends TestCase
{
@@ -26,6 +27,30 @@ class OrderTest extends TestCase
$this->assertEquals(2, $concert->ticketsRemaining());
}
/** @test */
function retrieving_an_order_by_confirmation_number()
{
$order = factory(Order::class)->create([
'confirmation_number' => 'ORDERCONFIRMATION1234',
]);
$foundOrder = Order::findByConfirmationNumber('ORDERCONFIRMATION1234');
$this->assertEquals($order->id, $foundOrder->id);
}
/** @test */
function retrieving_a_nonexistent_order_by_confirmation_number_throws_an_exception()
{
try {
Order::findByConfirmationNumber('NONEXISTENTCONFIRMATIONNUMBER');
} catch (ModelNotFoundException $e) {
return;
}
$this->fail('No matching order was found for the specified confirmation number, but an exception was not thrown.');
}
/** @test */
function converting_to_an_array()
{