[Catalyst] getting $c in model unit test
Matt Lawrence
matt.lawrence at ymogen.net
Wed May 16 10:11:56 GMT 2007
Nathan Gray wrote:
> On Tue, May 15, 2007 at 03:32:31PM +0100, Matt Lawrence wrote:
>
>> Nathan Gray wrote:
>>
>>> I would like to test a model with a unit test. Catalyst kindly
>>> generates stub unit tests for models, but it does not include a stub
>>> showing how to instantiate the context object.
>>>
>>>
>> I think I mentioned this on another thread earlier on. Something about
>> Chuck Norris if memory serves. Anyway:
>>
>> my $controller = MyApp->controller('MyController');
>> my $c = MyApp->prepare();
>>
>> # Monkey with $c to set up a fake context (set req->uri, or params)
>>
>> my $result = $c->forward($controller, 'method_to_test', \@args);
>>
>
> Thank you.
>
> We should probably add something like this to the autogenerated model
> test stub, which appears to work:
>
> use MyApp;
> my $model = MyApp->model('MyModel');
> my $c = MyApp->prepare();
>
> I tried to use the 'forward' method, but it did not want to cooperate
> (Modification of non-creatable array value attempted, subscript -1 at
> /usr/share/perl5/Catalyst/Dispatcher.pm line 186, which is: 'my
> $namespace = $c->stack->[-1]->namespace;').
>
Ah yes. You don't normally forward to a Model. If you're testing a
controller (or, I suppose, a view), it's best to forward, otherwise you
get a similar error if the controller method you're calling forwards to
another method itself.
> So rather than stubbing this example code:
>
> # Test each method of your model
> #is(
> # $c->forward($model, 'methodname_here', \@args_here),
> # $expected_value_here,
> # $test_description_here,
> #);
>
> we may want to stub in an example like this:
>
> # Test each method of your model
> #is(
> # $model->methodname_here($c, @args_here),
> # $expected_value_here,
> # $test_description_here,
> #);
>
Seems reasonable to me.
Cheers,
Matt
More information about the Catalyst
mailing list