diff --git a/mod/quiz/locallib.php b/mod/quiz/locallib.php
index aee52a7fc87..0ccdf0030dc 100644
--- a/mod/quiz/locallib.php
+++ b/mod/quiz/locallib.php
@@ -2411,13 +2411,13 @@ function quiz_prepare_and_start_new_attempt(quiz $quizobj, $attemptnumber, $last
         $offlineattempt = false, $forcedrandomquestions = [], $forcedvariants = [], $userid = null) {
     global $DB, $USER;
 
-    $ispreviewuser = false;
-
-    // Delete any previous preview attempts belonging to this user.
     if ($userid === null) {
         $userid = $USER->id;
         $ispreviewuser = $quizobj->is_preview_user();
+    } else {
+        $ispreviewuser = has_capability('mod/quiz:preview', $quizobj->get_context(), $userid);
     }
+    // Delete any previous preview attempts belonging to this user.
     quiz_delete_previews($quizobj->get_quiz(), $userid);
 
     $quba = question_engine::make_questions_usage_by_activity('mod_quiz', $quizobj->get_context());
diff --git a/mod/quiz/tests/attempt_test.php b/mod/quiz/tests/attempt_test.php
index 91b68e0b7e3..45df731bf3c 100644
--- a/mod/quiz/tests/attempt_test.php
+++ b/mod/quiz/tests/attempt_test.php
@@ -316,6 +316,7 @@ class mod_quiz_attempt_testcase extends advanced_testcase {
      * Test quiz_prepare_and_start_new_attempt function
      */
     public function test_quiz_prepare_and_start_new_attempt() {
+        global $USER;
         $this->resetAfterTest();
 
         // Create course.
@@ -358,5 +359,9 @@ class mod_quiz_attempt_testcase extends advanced_testcase {
         $attempt = quiz_prepare_and_start_new_attempt($quizobj, 2, null, false, [], [], $student2->id);
         $this->assertEquals($student2->id, $attempt->userid);
         $this->assertEquals(0, $attempt->preview);
+        // Create attempt for user id that the same with current $USER->id.
+        $attempt = quiz_prepare_and_start_new_attempt($quizobj, 2, null, false, [], [], $USER->id);
+        $this->assertEquals($USER->id, $attempt->userid);
+        $this->assertEquals(1, $attempt->preview);
     }
 }