diff --git a/course/tests/behat/keyholder.feature b/course/tests/behat/keyholder.feature
index db2f6e31ad5..229cebfd82f 100644
--- a/course/tests/behat/keyholder.feature
+++ b/course/tests/behat/keyholder.feature
@@ -1,61 +1,53 @@
-@core @core_course @javascript
+@core @core_course
 Feature: Keyholder role is listed as course contact
   As a student I need to know who the keyholder is to enrol in a course
 
   Background:
-    Given I log in as "admin"
-    And I am on site homepage
+    Given the following "roles" exist:
+        | shortname | name      | archetype | context_coursecat | context_course | enrol/self:holdkey |
+        | keyholder | Keyholder |           | 1                 | 1              | allow              |
     And the following "categories" exist:
       | name | category | idnumber |
       | Cat 1 | 0 | CAT1 |
-    And I navigate to "Users > Permissions > Define roles" in site administration
-    And I click on "Add a new role" "button"
-    And I click on "Continue" "button"
-    And I set the following fields to these values:
-    | Short name | keyholder |
-    | Custom full name | Keyholder |
-    | contextlevel40 | 1 |
-    | contextlevel50 | 1 |
-    | enrol/self:holdkey | 1 |
-    And I click on "Create this role" "button"
-    And I navigate to "Appearance > Courses" in site administration
-    And I click on "Keyholder" "checkbox"
-    And I press "Save changes"
     And the following "users" exist:
-      | username | firstname | lastname | email |
-      | teacher1 | Teacher | 1 | teacher1@example.com |
-      | keyholder1 | Keyholder | 1 | keyholder1@example.com |
-      | student1 | Student | 1 | teacher1@example.com |
+      | username   | firstname | lastname | email                  |
+      | teacher1   | Teacher   | 1        | teacher1@example.com   |
+      | keyholder1 | Keyholder | 1        | keyholder1@example.com |
+      | student1   | Student   | 1        | teacher1@example.com   |
     And the following "courses" exist:
       | fullname | shortname | format | coursedisplay | numsections | category |
       | Course 1 | C1 | topics | 0 | 5 | CAT1 |
     And I add "Self enrolment" enrolment method in "Course 1" with:
+      | Course 1 | C1        | topics | 0             | 5           | CAT1     |
+    When I log in as "admin"
+    And I navigate to "Appearance > Courses" in site administration
+    And I set the following fields to these values:
+      | Keyholder | 1 |
+    And I press "Save changes"
+    And I am on "Course 1" course homepage
+    And I add "Self enrolment" enrolment method with:
       | Custom instance name | Test student enrolment |
-      | Enrolment key | letmein |
+      | Enrolment key        | letmein                |
     And I log out
 
   Scenario: Keyholder assigned to a course
-    When I log in as "admin"
-    And the following "course enrolments" exist:
-      | user | course | role |
-      | teacher1 | C1 | editingteacher |
-      | keyholder1 | C1 | keyholder |
-    And I log out
-    And I log in as "student1"
+    Given the following "course enrolments" exist:
+      | user       | course | role           |
+      | teacher1   | C1     | editingteacher |
+      | keyholder1 | C1     | keyholder      |
+    When I log in as "student1"
     And I am on site homepage
     And I follow "Course 1"
     Then I should see "Keyholder 1"
 
   Scenario: Keyholder assigned to a category
-    When I log in as "admin"
-    And the following "role assigns" exist:
-      | user    | role          | contextlevel | reference |
-      | keyholder1 | keyholder       | Category     | CAT1      |
+    Given the following "role assigns" exist:
+      | user       | role      | contextlevel | reference |
+      | keyholder1 | keyholder | Category     | CAT1      |
     And the following "course enrolments" exist:
-      | user | course | role |
-      | teacher1 | C1 | editingteacher |
-    And I log out
-    And I log in as "student1"
+      | user     | course | role           |
+      | teacher1 | C1     | editingteacher |
+    When I log in as "student1"
     And I am on site homepage
     And I follow "Course 1"
     Then I should see "Keyholder 1"
diff --git a/enrol/self/tests/behat/key_holder.feature b/enrol/self/tests/behat/key_holder.feature
index 46b1efb0702..1186760b0de 100644
--- a/enrol/self/tests/behat/key_holder.feature
+++ b/enrol/self/tests/behat/key_holder.feature
@@ -5,23 +5,17 @@ Feature: Users can be defined as key holders in courses where self enrolment is
   I need to auto enrol me in courses
 
   Background:
-    Given the following "users" exist:
+    Given the following "roles" exist:
+        | shortname | name       | archetype | context_course | enrol/self:holdkey |
+        | keyholder | Key holder |           | 1              | allow              |
+    And the following "users" exist:
       | username | firstname | lastname | email |
       | manager1 | Manager | 1 | manager1@example.com |
       | student1 | Student | 1 | student1@example.com |
     And the following "courses" exist:
       | fullname | shortname | format |
-      | Course 1 | C1 | topics |
+      | Course 1 | C1        | topics |
     And I log in as "admin"
-    And I navigate to "Users > Permissions > Define roles" in site administration
-    And I click on "Add a new role" "button"
-    And I click on "Continue" "button"
-    And I set the following fields to these values:
-      | Short name | keyholder |
-      | Custom full name | Key holder |
-      | contextlevel50 | 1 |
-      | enrol/self:holdkey | 1 |
-    And I click on "Create this role" "button"
     And I navigate to "Appearance > Courses" in site administration
     And I set the following fields to these values:
       | Key holder | 1 |
@@ -38,11 +32,13 @@ Feature: Users can be defined as key holders in courses where self enrolment is
       | Custom instance name | Test student enrolment |
       | Enrolment key | moodle_rules |
     And I log out
-    And I log in as "student1"
+
+  Scenario: The key holder name is displayed on site home page
+    Given I log in as "student1"
     And I am on "Course 1" course homepage
     And I should see "You should have received this enrolment key from:"
     And I should see "Manager 1"
-    And I set the following fields to these values:
+    When I set the following fields to these values:
       | Enrolment key | moodle_rules |
     And I press "Enrol me"
     Then I should see "Topic 1"
diff --git a/lib/testing/generator/data_generator.php b/lib/testing/generator/data_generator.php
index 92e5e79e02b..9715800546a 100644
--- a/lib/testing/generator/data_generator.php
+++ b/lib/testing/generator/data_generator.php
@@ -789,7 +789,20 @@ EOD;
         // If no archetype was specified we allow it to be added to all contexts,
         // otherwise we allow it in the archetype contexts.
         if (!$record['archetype']) {
-            $contextlevels = array_keys(context_helper::get_all_levels());
+            $contextlevels = [];
+            $usefallback = true;
+            foreach (context_helper::get_all_levels() as $level => $title) {
+                if (array_key_exists($title, $record)) {
+                    $usefallback = false;
+                    if (!empty($record[$title])) {
+                        $contextlevels[] = $level;
+                    }
+                }
+            }
+
+            if ($usefallback) {
+                $contextlevels = array_keys(context_helper::get_all_levels());
+            }
         } else {
             // Copying from the archetype default rol.
             $archetyperoleid = $DB->get_field(
@@ -802,7 +815,6 @@ EOD;
         set_role_contextlevels($newroleid, $contextlevels);
 
         if ($record['archetype']) {
-
             // We copy all the roles the archetype can assign, override, switch to and view.
             if ($record['archetype']) {
                 $types = array('assign', 'override', 'switch', 'view');
@@ -820,6 +832,31 @@ EOD;
             role_cap_duplicate($sourcerole, $newroleid);
         }
 
+        $allcapabilities = get_all_capabilities();
+        $foundcapabilities = array_intersect(array_keys($allcapabilities), array_keys($record));
+        $systemcontext = \context_system::instance();
+
+        $allpermissions = [
+            'inherit' => CAP_INHERIT,
+            'allow' => CAP_ALLOW,
+            'prevent' => CAP_PREVENT,
+            'prohibit' => CAP_PROHIBIT,
+        ];
+
+        foreach ($foundcapabilities as $capability) {
+            $permission = $record[$capability];
+            if (!array_key_exists($permission, $allpermissions)) {
+                throw new \coding_exception("Unknown capability permissions '{$permission}'");
+            }
+            assign_capability(
+                $capability,
+                $allpermissions[$permission],
+                $newroleid,
+                $systemcontext->id,
+                true
+            );
+        }
+
         return $newroleid;
     }
 
diff --git a/user/tests/behat/user_grade_navigation.feature b/user/tests/behat/user_grade_navigation.feature
index 192fd5942c5..dda9119b3e0 100644
--- a/user/tests/behat/user_grade_navigation.feature
+++ b/user/tests/behat/user_grade_navigation.feature
@@ -59,22 +59,13 @@ Feature: The student can navigate to their grades page and user grade report.
     Then I should see "My badges from Acceptance test site web site"
 
   Scenario: Log in as a parent and view a childs grades.
+    Given the following "roles" exist:
+      | shortname | name   | archetype | context_user | moodle/user:editprofile | moodle/user:viewalldetails | moodle/user:viewuseractivitiesreport | moodle/user:viewdetails |
+      | Parent    | Parent |           | 1            | allow                   | allow                      | allow                                | allow                   |
     When I log in as "admin"
     And I am on site homepage
     And I turn editing mode on
     And I add the "Mentees" block
-    And I navigate to "Users > Permissions > Define roles" in site administration
-    And I click on "Add a new role" "button"
-    And I click on "Continue" "button"
-    And I set the following fields to these values:
-    | Short name | Parent |
-    | Custom full name | Parent |
-    | contextlevel30 | 1 |
-    | moodle/user:editprofile | 1 |
-    | moodle/user:viewalldetails | 1 |
-    | moodle/user:viewuseractivitiesreport | 1 |
-    | moodle/user:viewdetails | 1 |
-    And I click on "Create this role" "button"
     And I am on the "student1" "user > profile" page
     And I click on "Preferences" "link" in the ".profile_tree" "css_element"
     And I follow "Assign roles relative to this user"
diff --git a/user/tests/behat/view_preferences_page.feature b/user/tests/behat/view_preferences_page.feature
index 681738b73b8..64489442ee2 100644
--- a/user/tests/behat/view_preferences_page.feature
+++ b/user/tests/behat/view_preferences_page.feature
@@ -52,22 +52,13 @@ Feature: Access to preferences page
     Then I should see "Preferences" in the "region-main" "region"
 
   Scenario: A user with the appropriate permissions can view another user's permissions page.
-    Given I log in as "admin"
+    Given the following "roles" exist:
+      | shortname | name   | archetype | context_user | moodle/user:editprofile | moodle/user:viewalldetails | moodle/user:viewuseractivitiesreport | moodle/user:viewdetails |
+      | Parent    | Parent |           | 1            | allow                   | allow                      | allow                                | allow                   |
+    When I log in as "admin"
     And I am on site homepage
     And I turn editing mode on
     And I add the "Mentees" block
-    And I navigate to "Users > Permissions > Define roles" in site administration
-    And I click on "Add a new role" "button"
-    And I click on "Continue" "button"
-    And I set the following fields to these values:
-    | Short name | Parent |
-    | Custom full name | Parent |
-    | contextlevel30 | 1 |
-    | moodle/user:editprofile | 1 |
-    | moodle/user:viewalldetails | 1 |
-    | moodle/user:viewuseractivitiesreport | 1 |
-    | moodle/user:viewdetails | 1 |
-    And I click on "Create this role" "button"
     And I am on the "student1" "user > profile" page
     And I click on "Preferences" "link" in the ".profile_tree" "css_element"
     And I follow "Assign roles relative to this user"