This feature seems to have went under the radar, so here's a guide to clean and simple fork tests with foundry.
No custom profiles, tailored file names/directory structure, or match flags needed 👇️
1/ In your foundry.toml, create an `[rpc_endpoints]` table. The key is your alias for the network, the value is the RPC URL for that network. Env vars are supported using the syntax shown:
[rpc_endpoints]
mainnet = "${MAINNET_RPC_URL}"
optimism = "${OPTIMISM_RPC_URL}"
2/ In your test file, do something like this:
contract MyToken_ForkTests {
uint forkId;
function setUp() public {
uint forkBlock = 15_000_000;
forkId = vm.createSelectFork(vm.rpcUrl("mainnet"), forkBlock);
}
function testSomething () public {}
}
3/ How it works: `vm.createSelectFork` creates the fork at the specified block number using the "mainnet" RPC URL specified in foundry.toml, returns the ID of that fork, and makes it active.
Now, all fork tests in that contract run against mainnet state.
4/ Since an (optional) block number was passed, RPC responses are cached to speed up future test runs.
You can also change forks in a test as shown. Contracts deployed on a fork only exist on that fork. The makePersistent cheat lets you mark addresses to persist across forks.
6/ Be consistent with test/contract naming conventions: if you're offline and can't run fork tests, good naming conventions let you use the `--no-match*-` flags to skip anything with "fork" in its name
Credit to @mattsse_ for implementing to make fork tests super easy 👌