Share

Testing domains with Rails and Test-Unit

I'm currently working on a Ruby on Rails project where sub-domains come into play pretty heavily. Each account created on the site has its own sub-domain, which means that there is no pre-set list. I ran into some problems when writing functional tests and integration tests with Capybara, as I had no idea how to set the current domain and assert a change in sub-domain. Fortunately, after struggling through for a couple of hours, I found the solution and I'm putting it here for the benefit of anyone else!

Setting the domain in functional tests

To set the domain in test-unit tests, use the @request.host variable inside the test method:

# test/functional/accounts_controller.rbclassAccountsControllerTest<ActionController::TestCasetest"something to do with an account"doaccount=FactoryGirl.create:accountuse_accountaccount#... rest of testendend

Setting the domain in integration tests with Capybara

If you aren't using Capybara, you can simply set the current host in integration tests with the host! method:

# test/integration/domain.rbclassDomainTest<ActionDispatch::IntegrationTesttest"bad subdomain redirects to main domain with Capybara"doCapybara.app_host='http://lkjasdasd.domain.com'visitroot_pathassert_equal'http://domain.com/',current_urlendend

Thanks for reading. Why not share this post? Or Follow @joonty for updates