This paper proposes a class of optimal tests for the constancy of parameters in random coefficients models. Our testing procedure covers the class of Hamilton's models, where the parameters vary according to an unobservable Markov chain, but also applies to nonlinear models where the random coefficients need not be Markov. We show that the contiguous alternatives converge to the null hypothesis at a rate that is slower than the standard rate. Therefore, standard approaches do not apply. We use Bartlett-type identities for the construction of the test statistics. This has several desirable properties. First, it only requires estimating the model under the null hypothesis where the parameters are constant. Second, the proposed test is asymptotically optimal in the sense that it maximizes a weighted power function. We derive the asymptotic distribution of our test under the null and local alternatives. Asymptotically valid bootstrap critical values are also proposed.