[rspec-users] How are people speccing Rails 3 ActiveRecord queries?
dchelimsky at gmail.com
Sat Jul 17 12:11:01 EDT 2010
On Jul 17, 2010, at 10:37 AM, doug livesey wrote:
> Hi -- how are people speccing Rails 3 ActiveRecord queries?
> At the minute I'm chaining a load of should_receive calls on mock relation objects, but can't help thinking that there must be a more elegant way of going about it.
> Is there a best practice for this, yet?
For me, there is only one best practice: think. Everything else is a guideline in some context.
That said, here are some of my guidelines, in context. YMMV.
My approach to spec'ing models is different from that for controllers and views. In controller and view specs I prefer to stub out the data layer most of the time because I don't want the controller/view specs failing due to things like validations, which are model concerns.
Spec'ing models is a different animal. I'll still use stubs where they make sense, but I'm perfectly happy using real objects and interacting with the database when spec'ing behavior that is influenced by the db and relationships between models.
I prefer to think of spec'ing behavior rather than spec'ing query details. A simple example would be querying for the "active" members of a group. We could say:
Member.should_receive(:where).with(:active => true)
Or, we could say:
active_member = Factory(:member, :active => true)
inactive_member = Factory(:member, :active => false)
I, personally, find the latter more expressive, and we don't have to worry about the details of AR in the specs.
More information about the rspec-users