title: Laravel Unit testing Eloquent insertion
body: <p>I'm currently having some troubles in testing a function in Laravel. This function is a simple save user function.</p>
  
  <p>The current structure involves a User</p>
  
  <pre><code>class User extends Authenticatable
  </code></pre>
  
  <p>Then I have a UserController</p>
  
  <pre><code>class UserController extends Controller
  {
  protected $user;
  
  public function __construct(User $user)
  {
      $this-&gt;user = $user;
      $this-&gt;middleware('admins');
  }
  </code></pre>
  
  <p>The save function is defined on the UserController class, this class only assigns the request variables and uses Eloquent save function to save to database.</p>
  
  <p>The function signature is the following:</p>
  
  <pre><code>public function storeUser($request)
  {
  
      $this-&gt;user-&gt;name       = $request-&gt;name;
      $this-&gt;user-&gt;email      = $request-&gt;email;
      $this-&gt;user-&gt;country_id = $request-&gt;country_id;
  
      return $this-&gt;user-&gt;save();
  }
  </code></pre>
  
  <p>The NewAccountRequest object extends from Request and has the validation rules for the request.</p>
  
  <pre><code>class NewAccountRequest extends Request
  {
  public function authorize()
  {
      return true;
  }
  
  public function rules()
  {
      return [
          'name' =&gt; 'required|max:255',
          'email' =&gt; 'required|email|max:255|unique:user',
          'password' =&gt; 'required|min:6|max:60',
      ];
  }
  
  }
  </code></pre>
  
  <p>My problem is how can I unit test this storeUser function.</p>
  
  <p>I have the current test:</p>
  
  <pre><code>public function testSaveUserWithEmptyRequest()
  {
  
      $user = $this-&gt;createMock(User::class);
      $controller = new UserController($user);
  
      $request = $this-&gt;createMock(NewAccountRequest::class);
      $store = $controller-&gt;storeUser($request);
  
      $this-&gt;assertFalse($store);
  }
  </code></pre>
  
  <p>I'm mocking both User and NewAccountRequest, the problem is that the assertion should be false, from the Eloquent save. Instead I'm getting Null. Any idea on how can I correctly test the function?</p>