InteractsWithDatabase.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace Tests;
  3. trait InteractsWithDatabase
  4. {
  5. /**
  6. * Assert that a given where condition exists in the database.
  7. *
  8. * @param string $table
  9. * @param array $data
  10. * @param string $connection
  11. * @return $this
  12. */
  13. protected function seeInDatabase($table, array $data, $connection = null)
  14. {
  15. $database = $this->app->make('db');
  16. $connection = $connection ?: $database->getDefaultConnection();
  17. $count = $database->connection($connection)->table($table)->where($data)->count();
  18. $this->assertGreaterThan(0, $count, sprintf(
  19. 'Unable to find row in database table [%s] that matched attributes [%s].', $table, json_encode($data)
  20. ));
  21. return $this;
  22. }
  23. /**
  24. * Assert that a given where condition does not exist in the database.
  25. *
  26. * @param string $table
  27. * @param array $data
  28. * @param string $connection
  29. * @return $this
  30. */
  31. protected function missingFromDatabase($table, array $data, $connection = null)
  32. {
  33. return $this->notSeeInDatabase($table, $data, $connection);
  34. }
  35. /**
  36. * Assert that a given where condition does not exist in the database.
  37. *
  38. * @param string $table
  39. * @param array $data
  40. * @param string $connection
  41. * @return $this
  42. */
  43. protected function dontSeeInDatabase($table, array $data, $connection = null)
  44. {
  45. return $this->notSeeInDatabase($table, $data, $connection);
  46. }
  47. /**
  48. * Assert that a given where condition does not exist in the database.
  49. *
  50. * @param string $table
  51. * @param array $data
  52. * @param string $connection
  53. * @return $this
  54. */
  55. protected function notSeeInDatabase($table, array $data, $connection = null)
  56. {
  57. $database = $this->app->make('db');
  58. $connection = $connection ?: $database->getDefaultConnection();
  59. $count = $database->connection($connection)->table($table)->where($data)->count();
  60. $this->assertEquals(0, $count, sprintf(
  61. 'Found unexpected records in database table [%s] that matched attributes [%s].', $table, json_encode($data)
  62. ));
  63. return $this;
  64. }
  65. /**
  66. * Seed a given database connection.
  67. *
  68. * @param string $class
  69. * @return void
  70. */
  71. public function seed($class = 'DatabaseSeeder')
  72. {
  73. $this->artisan('db:seed', ['--class' => $class]);
  74. }
  75. }