[SalesForce] Account sharing rule not working in apex code

I've set up Account sharing rules so that if a checkbox field is false, Accounts are Read/Write for All Internal Users.
I have a Profile (thisProfile) where all CRUD operations are ticked, but not view/modify all.

This seems to be working within the UI for this particular profile because they can view all relevant Accounts/Contacts, however I also have a class that has 'with sharing' set but access to relevant records is not working. In a simple case, my test class creates 2 Accounts, then using runas(thisProfile) a basic [SELECT Id FROM Account] query returns no results.

If I turn on view all, it then works but this opens up access to a number of records that should not be shared.

Any ideas on how to troubleshoot this, or what could be causing it?

Best Answer

Based on you post it appears you are having this issue during test method execution.

Ran into this same issue and it is a shame it is not supported:

Also, criteria-based sharing cannot be tested using Apex.

https://help.salesforce.com/HTViewHelpDoc?id=security_sharing_cbs_about.htm&language=en_US

Basically, only OWD Sharing rules are enforced. Also, runAs does NOT enforce crud so you will have to use describe methods to verify FLS

The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing. (keeping in mind above)

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_tools_runas.htm

One workaround I built was to create a custom setting to hold a userID, a record id, and checkboxes for read, edit, delete, all and a text box for maxaccess.

Then I created a test class to cycle through all the settings records I created and ensured the user had appropriate access to existing records using userrecordaccess. Not ideal, but it sudo ensure the criteria sharing rules are working as expected for Identified records. By setting the specific records you can also troubleshoot any issues much eaiser. (If a test record fails I put the custom setting record ID int he assert so I can go directly to the affected records.)

Related Topic