Spring ’16 Feature – Run Scripts for Sandbox

A neat feature in the Salesforce Spring ’16 release is the Run Script after Sandbox Create or Refresh.  This could be helpful for environments that need some dummy data or static data populated in developer, partial, or full sandbox.

Let’s take the following very simple use case.  Another update with Spring’16 is the increase number of developer sandboxes.  Now we have the ability to create 25 at a time.  Because developer sandboxes do not copy record data with it, if you need let’s say Accounts then its up to you to create them each time you spin up a sandbox.  With this new sandbox script feature we could automate creating test Accounts.

For this example, I’m going to create 10 Accounts when a sandbox is created or refreshed.  To do this I’ll need to build an apex class that implements the SandboxPostCopy interface.  Inside I’ll loop through and build 10 accounts with some sample data.


global class sandboxRefreshScript implements SandboxPostCopy
{
global void runApexClass(SandboxContext context)
{

List<Account> accounts = new List<Account>();
for(Integer x = 1; x < 11; x++)
{
Account a = new Account();
a.Name = 'Test Account ' + x;
a.Type = 'Client';
a.BillingState = 'NC';
a.BillingCity = 'Greensboro';

accounts.add(a);
}

insert accounts;
}
}

…and of course we need a test class with it.  Under the Test class we now have the method testSandboxPostCopyScript in which we pass the SandboxPostCopy class,  Id’s for sandbox Id and org Id, along with a sandbox name.


@isTest
private class sandboxRefreshScriptTest
{
@isTest static void testScriptRun()
{
system.assertequals(0, [Select count() from Account]);

sandboxRefreshScript sandboxScriptclass = new sandboxRefreshScript();
Test.testSandboxPostCopyScript(sandboxScriptclass, UserInfo.getOrganizationId(), UserInfo.getOrganizationId(), 'sandboxName');

system.assertequals(10, [Select count() from Account]);
}

}

 

When we create or refresh a sandbox we now have the following option to attach a sandbox script.

selectsandboxscript

After my sandbox has been created, I can see I now have 10 accounts!

Screen Shot 2016-04-07 at 8.29.18 AM

 

Two additional notes:

1.) When you sandbox is activated (manual or auto) you should receive a second email saying that your script has run.

Screen Shot 2016-04-07 at 8.32.13 AM

2.) For record insertion, keep in mind the owner will not be the person that started the sandbox create/refresh.  The owner will be “Automated Process”.