Wednesday, June 2, 2010

Cucumber and Subdomains Revisited (the Capybara chronicles)

Well, I've been working steadily on RoR development for the last year.  I finally landed a job in November as a full time RoR developer, and it's AWESOME!

But that's not the point of this post.  In my last post, I had just figured out how to get Cucumber with Webrat to work with subdomains.  Then I needed to test JS.  But I don't want to run Selenium or Culerity or anything else for ALL my tests.  That would be waaaaay to slow.  Sooooo....over to Capybara I go.

And guess what?  Just about every test failed, because subdomains don't work the same.  Crap!  I'm not knocking Capybara.  I think it's awesome.  The benefits far outweigh this little foible for sure!  I just didn't anticipate this issue.

Just to be clear, the issue is not calling a 'visit' to a hard-coded url with a subdomain.  That's easy and seems to work just fine.  It's when you get redirected to other pages after that.  The subdomain isn't carried along and things start to break down.

So off to the research pits I go.  And I don't find much that helps.  Capybara's Github page does give a suggestion (https://gist.github.com/643a758320a2926bd2ed) about how to handle this with default_url_options.  I tried it.  I couldn't get it to work.  And I didn't really like it anyway.  Probably not a big deal, but it just offends my sensibilities to change code for tests.  Back to Google...still nothing.

So off to the Capybara code itself.  After some digging, I've come up with this solution using default_host and app_host that handles subdomains for the regular Capybara tests (Rack::Test) and for Capybara's Culerity driver.  Don't forget to add entries to your /etc/hosts file for all of the subdomains you'll be using with Culerity, or things will go boom.

One thing I'd like to improve about this is the port being a variable pulled from Capybara somehow (instead of hard-coded to 9887), but I couldn't figure out how to do that, and it isn't terribly important to me right now.  I'll be happy to update the gist if anyone figures this out.  Just let me know.

I didn't test this with any of the other drivers (like Selenium) because I'm only using Culerity so far.  Haven't had any reason to do any others yet.  If anyone else tests this with any of the other drivers, let me know, and I'll edit the post with that info.

Edit
Got a question about what relevant gems I'm using and realized that was important information!  So here they are:

Cucumber - 0.7.2
Capybara - 0.3.8
Langalex's Culerity - 0.2.10