Testable code with ORM factory
(I've not coded in PHP recently, my examples are Java or Java-like pseudocode.)

In his Working Effectively with Legacy Code book Michael C. Feathers describes a lot of techniques which help making any code testable. Another good resource is the following article: Killing the Helper class, part two

The usual way to breaking static dependencies is the following: Create a non-static interface which has a similar method than the original static class:

public interface OrmFactory {
    OrmSomething create($name);
}


Then create an implementation which calls the static method/class:

public class OrmFactoryImpl implements OrmFactory {
    public OrmSomething create($name) {
        return ORM::factory($name);
    }
}


Finally, use the interface in the can_apply_extension function:

public class MyClass {

    private OrmFactory ormFactory;

    public MyClass(OrmFactory ormFactory) {
        this.ormFactory = ormFactory;
    }

    public void can_apply_extension() {
        ...
        $record = ormFactory.create('a model')
                     -&gt;where('created_at', 'BETWEEN', $search_dates)
                     -&gt;find();
        ...
    }
}


In tests you can pass a mocked OrmFactory to the class while in production code you can use the original one through the OrmFactoryImpl wrapper/delegate. (I guess PHP also has some mocking framework implementations which makes testing easier but you can implement a TestOrmFactory which emulates some behaviour of the original one without the need of any database.)

The second snippet in the question has test logic in production smell. I would avoid that and use the much cleaner dependency breaking above. The linked page contains some disadvantages of the smell. One of them is the following:


  Code that was not designed to work in production 
  and which has not been verified to work properly
  in the production environment could accidently be 
  run in production and cause serious problems. 


And another one is:


  Software that is added to the SUT For Tests Only 
  makes the SUT more complex. It can confuse potential
  clients of the software's interface by introducing
  additional methods that are not intended to be
  used by any code other than the tests. This 
  code may have been tested only in very specific 
  circumstances and might not work in the typical
  usage patterns used by real clients. 


(SUT means System Under Test, in this case the class with can_apply_extension().)