[rspec-users] Proper Encapsulation of SQL WHERE / ORDER BY Clauses

Scott Taylor mailing_lists at railsnewbie.com
Fri Aug 15 19:19:31 EDT 2008


On Aug 15, 2008, at 9:29 AM, David Chelimsky wrote:

> On Aug 15, 2008, at 6:46 AM, Matt Wynne <matt at mattwynne.net> wrote:
>
>> On 15 Aug 2008, at 12:25, David Chelimsky wrote:
>>
>>> Hey Matt - welcome!
>>>
>>> The paginate() method lives on the model class, so there's nothing
>>> stopping you from wrapping those calls in methods on the model,
>>> slinging around the params object.
>>>
>>> # CityController
>>>
>>> def get_cities
>>> City.paginate_all(params)
>>> end
>>>
>>> # City
>>>
>>> def self.paginate_all(params)
>>> self.paginate(:all, get_find_params(params).merge!(:page =>  
>>> params[:page]))
>>> end
>>>
>>> etc
>>>
>>
>> Aha. Cool, thanks.
>>
>> For my next question: how do I go about driving out change to the  
>> model, spec-first?
>>
>> I'm thinking I would call (in my spec)
>>
>>   City.should_receive(:paginate).with(:conditions => "name like  
>> '%#{test_params[:name}%'" .... )
>>   City.paginate_all(test_params)
>>
>> Thereby covering the code in get_find_params()
>>
>> Is that the right approach?
>
> That's probably how I would do it. Might also consider wrapping the  
> params in a separate object that manages the extraction.

That's how I've started doing it - putting sql statements in a module:

http://gist.github.com/5675

This allows me to test the sql statements seperately from the actual  
finder.

Also - just to give you the heads up - You should almost never use  
literal string substitutions in sql statements - it allows for sql  
injection attacks:

http://en.wikipedia.org/wiki/Sql_injection

Best,

Scott Taylor




More information about the rspec-users mailing list