2

I'm moving some Communities logic over to SFDX format and aiming to use a scratch org for a Continuous Integration build. The test cases I already have create a new User and verify that the User is correctly hooked up to a Contact/Account. I have this scratch org definition in place:

{
    "orgName": "cveep dev",
    "edition": "Developer",
    "features": ["Communities"],
    "settings": {
        "orgPreferenceSettings": {
            "networksEnabled": true,
            "s1DesktopEnabled": true
        }
    }
}

But to avoid this error in the tests:

portal account owner must have a role

I need to give the User that owns the Account a Role, but the simplest approach to that causes this error:

operation on setup object is not permitted after you have updated a non-setup object (or vice versa)

Is using sfdx data:record:create and sfdx data:record:update to setup the Role on the default User before the tests are run a good way to go? Is there a better way to solve this?

2 Answers 2

6

Seemed easiest to add an Apex method to an existing class:

public class UserBuilder {

    // Called from build code
    public static void ensureRole() {

        if (UserInfo.getUserRoleId() == null) {
            // Avoid "portal account owner must have a role" error
            UserRole ur = new UserRole(DeveloperName = 'PortalAccountOwnerRole', Name = 'Portal Account Owner Role');
            insert ur;
            update new User(Id = UserInfo.getUserId(), UserRoleId = ur.Id);
        }
    }

    ...
}

and call that from the Jenkinsfile:

stage('Push To Test Org') {
    sh "sfdx force:source:push --targetusername ${SFDC_USERNAME}"
}

stage('Add User Role') {
    sh "echo 'cveep.UserBuilder.ensureRole();' | sfdx force:apex:execute --targetusername ${SFDC_USERNAME}"
}

and this works i.e. the role is set up in a transaction before the tests run.

2
  • How do you invoke this method? possible to add as unit test? adding this to my unit tests cause this error - MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): UserRole, original object: Account: []
    – sfdx bomb
    May 28, 2019 at 13:32
  • Yes, the method needs to be called from a separate transaction; in our case that is a stage of a Jenkins Pipeline build. You can run manually first (e.g. from the Dev Console) if you are not using a CI server.
    – Keith C
    May 28, 2019 at 14:50
0

Finally managed to resolve this - had same issue.

Created new user in my scratch org using sfdx :

sfdx force:user:create --setalias qa-user 

Open the org went to Roles created a new Role and assigned it to new User. (apparently you cannot assign to existing role).

I'm now able to create Account with owner that has a role - which means I can create a portal account and contact for testing.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .