Search code examples
ruby-on-railsrubyrspecrakerspec-rails

Rails validation exclusion with routes


I want to test that a user is invalid if the username equals one of the first routing blocks. I spec it in rspec at the moment this way:

it "is not valid with a excluded username" do
  `bundle exec rake routes`.scan(/\s\/(\w+)/).flatten.compact.uniq.each do |route|
    user.username = route
    user.should_not be_valid
  end
end

The thing is, this slows down my specs, is there a better way to spec if every first route element is excluded?


Solution

  • The thing that slows down your specs is bundle exec rake routes, because it loads rails environment once again. To prevent this you can extract the code that displays routes from actual rake task (it can be found in rails github repo). With those modifications your spec could look like that:

    it "is not valid with a excluded username" do
      Rails.application.routes.routes.map(&:path).join("\n").scan(/\s\/(\w+)/).flatten.compact.uniq.each do |route|
        # blahblah
      end
    end