Wednesday, March 12, 2008

RSpec Dummyfication

When you're working with rspec and describing models relations you probably will need some dummy models, which wont bother you with all those validation stuffs. Yes, there's mock_model method, but the problem with it is that it stubs all the model methods first and the mocks don't have any relationships with the database.

And then if you need for your integration tests real models which will respond as real models and have database identification, you probably might find useful the following trick. Add the following strings into your spec_helper.rb file.

module Dummyficator
def dummy_inst(klass, attrs={ })
inst = attrs

include Dummyficator

After this you'll be able to create dummy model instances in your specs like that

describe Group, "with users" do
before do
@group = dummy_inst Group
@group << dummy_inst User
@group << dummy_inst User, :username => 'dummy'

it "should have two users" do
@group.should have(2).users

it "should not destroy users" do
User.find_by_username('dummy').should_not be_nil

This way you will be able to create new and new database records which will behave just as they should except the validation, so you can concentrate on the models relations not worrying about the models validation.

No comments: