How does a plant know what a rock looks like?
Humans always like to think of evolution as a cause & and-effect scenario, as if a plant or animal evolving is a conscious "response" to something else; as if the DNA code and genome of say, a mosquito that evolves insecticide resistance somehow "knows" what's happening to it and so it eventually produces the genes that code for resistance to the insecticide. This is obviously not what's going on. To think about it clearly we have to zoom way out on the times scales that we think of these things happening. We also have to think of the way that humans breed plants and *select* for the traits we like. Plant breeders may grow a thousand tomato plants, pick the three individuals that produce juicier tomatoes or show cold resistance, and throw out the other 997. That person will then breed the 3 seedlings they kept and then continue selecting for the traits they want and throwing out the rest. The environment does the exact same thing.
In the case of mosquitoes developing resistance to insecticide -- it's not as if the mosquitoe population "senses" that it is under attack and dtsrats actively producing mutations in its DNA that code for resistance against insecticides. The mutations that code for insect resistance were likely always there within the population, just to a much smaller degree and sometimes at greater frequencies within the population than at others, it's just that they never revealed themselves and certainly never spread to any significant degree BECAUSE there was no environmental stressor (in this case, the insecticide) to SELECT for them. There was no selection pressure acting on them.
Likewise, how does a cactus that comes to mimic a rock "know" what a rock looks like? The evolutionary pathway that put plants like Ariocarpus fissuratus on the trajectory of eventually coming to look like a rock never got accentuated in the distant ancestor of Ariocarpus UNTIL the climate started to dry out and aridify enough that a more mesic limestone environment (that may have been somewhat akin to the Edwards plateau) slowly began to shift towards a desert climate. It could have been the case that the ancestral, non-rock-mimicking ancestor of Ariocarpus fissuratus already grew on limestone but at a time before the extremely arid conditions developed and the general climate of the region was much more mesic. As the climate shifted towards aridity, the environment - with each passing generation of Ariocarpus plants - slowly selected for plants with a thicker cuticle and a more squat habit until, after many generations, we arrived at what we have today : a cactus that looks so much like a fucking rock that it can be hard to see even when you're literally standing right on top of it.