In a non-test environment, you can use casper.exit(2); to exit with a specific code.
In a test environment this is a little harder, because the execution is done in casper.test.begin functions.
For example, you can use the last test case in a file to set the exit code:
casper.test.begin("test desc 1", function(test){ ... }); ... casper.test.begin("test desc last", function(test){ casper.exit(2); });
It might be better to use the exit event handler, though.
var code = 0; casper.on("exit", function(code){ if (code > 0) { phantom.exit(2); // immediately exits } }); casper.test.begin("test desc 1", function(test){ ... if (!this.visible("something")) { code = 3; } ... }); ...