Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gem tests can't find route using url_for

I think the dummy app in which my gem tests are meant to run is not set up properly, because when I call url_for on a Gadget instance (a stub model from the dummy app) within the gem's helper, I get

undefined method `gadgets_path' for #<#<Class:0x007fe274bc1228>:0x007fe273d45eb0>

Background: I forked a gem and made some significant changes. (Here's the fork.) Now I'm trying to make the rspec tests work so I can verify my updates going forward.

The tests are set up like a Rails engine, with a dummy app within the spec directory. That app has one model (Gadget) with an appropriate controller and a resource declared in the spec/dummy/environment/routes.rb file:

Dummy::Application.routes.draw do
  resources :gadgets
end

The spec/spec_helper.rb file looks like this:

ENV["RAILS_ENV"] ||= "test"

require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'

require 'rspec/autorun'

RSpec.configure do |config|
  config.mock_framework = :rspec
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_base_class_for_anonymous_controllers = false
  config.order = "random"

  config.include Rails.application.routes.url_helpers
end

(You can actually see the full test setup in the project's github repo. I actually opened an issue for this a week or so ago, but only now am I getting around to trying to resolve it.)

The one test which isn't pending creates a Gadget instance, then calls the helper with that as an argument. When the helper tries url_for(@gadget), it triggers the above error.

What's wrong here?

ETA Dec 04: Updated with the current spec_helper.rb.

like image 527
pjmorse Avatar asked Dec 15 '22 17:12

pjmorse


1 Answers

Update

put this inside your spec_helper.rb - at least this works for me ( i cloned your repo )

ActionView::TestCase::TestController.instance_eval do
  helper Rails.application.routes.url_helpers#, (append other helpers you need)
end
ActionView::TestCase::TestController.class_eval do
  def _routes
    Rails.application.routes
  end
end

The real problem was that TestController was subclassed from ActionController::Base before ActionController::Base is extended with the route helper methods.
So you need to inject it back into the TestController. Furthermore AbstractController::UrlFor requires _routes to be implemented.


In order to use the routing helpers you should insert

Rspec.configure do |config|
  config.include Rails.application.routes.url_helpers
  ...
end

in your spec_helper.rb which makes all something_path methods available. Another way around the real issue would be to stub out the helper like so:

helper.stub!(:url_for).and_return("/path")
like image 75
krichard Avatar answered Dec 28 '22 06:12

krichard