jcasimir/draper — Issue #60: h#url_for within decorators is broken
Author: jperville
Created: 2011-10-21 13:57:48+00:00
State: open

Hi Casimir,

I am trying to to build URLs using #url_for from within a decorated model.
My decorator code looks like this:

```ruby
class UserDecorator < ApplicationDecorator
decorates :user

def admin_url
h.some_named_route_url(...)
end
end
```

When running the application in development or production the url is built from within the decorator just fine.
This is not the case when I run `rspec specs/decorators/user_decorator_spec.rb`. Here is what I get :

````
julien@dev:project$ rspec spec/decorators/user_decorator_spec.rb

UserDecorator
exposes an admin_url (FAILED - 1)

Failures:

1) UserDecorator exposes an admin_url
Failure/Error: puts "S => " + subject.admin_url.inspect
NoMethodError:
undefined method `host' for nil:NilClass
# ./app/decorators/user_decorator.rb:5:in `admin_url'
# ./spec/decorators/user_decorator_spec.rb:9:in `block (2 levels) in '

Finished in 0.3617 seconds
1 example, 1 failure
```

I read in issue #22 that you worked hard to make the 'view_context' accessible from within a decorator in the testing environment. This is the reason why the generated specs have the following line at the top :

```ruby
describe UserDecorator do
before { ApplicationController.new.set_current_view_context }
end
```

I think that the `NoMethodError` occurs because `ApplicationController.new` that you inject into the view_context does not embed any request object. So all the routes that need `request.host`, `request.protocol` etc... just fail with `NoMethodError` because `h.request` is `nil`.

I found an ugly hack to make url generation work as intended :

```ruby
describe UserDecorator do
before { c = ApplicationController.new
c.request = ActionDispatch::TestRequest.new
c.set_current_view_context}
end
```

I believe that if my use case works using real requests (in development or production) it should also work when testing using a dummy request. How would you integrate my workaround cleanly into draper ?

Thank you for sharing draper with me.

Sincerely,
Julien