[LRUG] Parameterising a Rails 3 controller mixin

Steve Tooke steve.tooke at gmail.com
Wed Oct 5 00:01:17 PDT 2011


Hi Andy,

On Tue, Oct 4, 2011 at 4:04 PM, Andrew Stewart <boss at airbladesoftware.com>wrote:

>
> On 4 Oct 2011, at 15:54, Graham Ashton wrote:
> > On 4 Oct 2011, at 14:53, Andrew Stewart wrote:
> > So change the name, run the one test you do have, then change it back
> without hard coding it. There's not enough win in that extra test.
>
>
> I'm going to do this...not because there's not enough benefit but because I
> can't figure out how to do it programatically!
>

Its usually difficult to test things which are not well isolated. One
approach you could take is to inject the model name into something which
creates the module for you. So your isolated test for the 'module' behaviour
could look something like this:

describe 'a ControllerMixin' do
  it 'adds a current bar method' do
*    *controller = double(session: {current_bar_id: 99})
    controller.extend ControllerMixin('bar')
    Foo.should_receive(:find).with(99)
    controller.current_bar
  end
end


You can then generate an anonymous module which has the correct method
defined:

def ControllerMixin(model)
  model_class = model.classify.constantize
  Module.new do
    define_method(:"current_#{model}") do
      model_class.find(session[:"current_#{model}_id"]) if
session[:"current_#{model}_id"]
    end
  end
end
*
*

You would then need to test how the module is included into
ActionController::Base but not necessarily the actual behaviour it would
give you. Having said that you would probably want some integration tests
for the particular rails app the engine was used in.

Its definitely a bit more complex, but it is more isolated, and therefore
easier to test - and less coupled to an attribute on a different class.

Steve
-- 
/tooky
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20111005/e5bab0e9/attachment.html>


More information about the Chat mailing list