views:

122

answers:

1

Is there some way to change Rails environments mid-way through a test? Or, alternately, what would be the right way to set up a test suite that can start up Rails in one environment, run the first half of my test in it, then restart Rails in another environment to finish the test? The two environments have separate databases.

Some necessary context: I'm writing a Rails plugin that allows multiple installations of a Rails app to communicate with each other with user assistance, so that a user without Internet access can still use the app. They'll run a local version of an app, and upload their work to the online app by saving a file to a thumbdrive and taking it to an Internet cafe.

The plugin adds two special environments to Rails: "offline-production" and "offline-test". I want to write functional tests that involve both the "test" and "offline-test" environments, to represent the main online version of the app and the local offline version of the app respectively.

Edit: I've been reading up on Rack::Test, and it seems like it might be the way to go, because it places the testing framework outside of rails itself. But I still have no idea how I can use it to do a test that involves more than one environment. Any ideas, anyone?

A: 

Maybe think about the issue from the perspective of having more than one db connection, instead of having more than one environment? You can't really switch environments part way through, at least without a lot of hacking and screwing things up. :)

http://anandmuranal.wordpress.com/2007/08/23/multiple-database-connection-in-rails/

Steven Soroka
Hmm, so I can call establish_connection again to change which database is currently being used by a model? That's most of what I need, but not quite all of it: there is some environment-specific behavior I'm testing (i.e. the online app is allowed to read but not alter data that originated in the offline app, and vice versa). Though, I suppose I can stub the environment-checking method to do that; that would work fine. Thanks much! :-)Actually, since I asked this question, I ended up doing it a different way: I use fork within my Rakefile to start separate Rails environments.
DSimon
You could stub Rails.env.development? as Rails.env.stub!(:development?).and_return(true) I suppose. Doesn't seem like a best practice though. Rather than having your code depend on environments, you can have it depend on configurations that your environment sets, which are much easier to change for testing.
Steven Soroka
That's an excellent idea, thanks.
DSimon