Testing dynamic routes that depends on the database on a Rails app
Today I was adding tests for some of new routes in our rails application (an 8-years-old rails 2.3 app)
In our case some of the routes depends on the database content:
ActionController::Routing::Routes.draw do |map| ... aliases = Site.all_sites.collect {|site| site.settings.aliases.keys}.flatten.uniq.compact aliases.each do |alias| map.connect "#{alias}", :controller => "foo", :action => 'bar', :alias => alias.to_s ... end ... end
And I found an interesting issue, my new routing spec passes when I run it alone, but it fails when I run all the specs.
What was happening is that rake spec
was loading the rails environment (routes.rb
included), and later the fixtures (or factories)
So, the data was not there when the routes.rb
was loaded
To solve it I just reload the routes in the spec:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe "New Routes" do before do ActionController::Routing::Routes.reload! # We need this b/c the routes depends on the DB end ... end