ruby on rails - RSpec stubs & mocks on related (belongs_to) relationships -


i'm trying head around rspec's incredibly confusing, @ least initially, syntax trying expand on default specs generated rails 3 scaffolding...

i have associated models...very simply:

#clown.rb class clown < activerecord::base   has_many :rabbits end  #rabbit.rb class rabbit < activerecord::base   belongs_to :clown end 

but i'm having trouble rabbits_controller.spec.rb. in specs fail when reference, say, clown.name in 1 of rabbit's views. stupid simple app works expected specs fail because haven't stubbed (or mocked?) clown respond correctly rabbit (or @ least that's think happening)?!? how should adding stub (or mocking clown rabbit associate to?).

existing:

   #rabbits.controller.spec.rb     require 'spec_helper'      describe rabbitscontroller        def mock_rabbit(stubs={})         (@mock_rabbit ||= mock_model(rabbit).as_null_object).tap |rabbit|           rabbit.stub(stubs) unless stubs.empty?         end       end        describe "get index"         "assigns rabbits @rabbits"           rabbit.stub(:all) { [mock_rabbit] }           :index           assigns(:rabbits).should eq([mock_rabbit])         end       end    ... 

imho (and there other points of view) isn't mocking or stubbing situation. mocks , stubs great external dependencies (think web service), internal application. want factory_girl, let create test data without headaches of fixtures or trying mock out every dependent relationship, becomes monotonous. factory_girl has great documentation, briefly here's factories might like:

factory.define(:clown) |f|   f.rabbits{|c| [c.assocation(:rabbit)]}   f.name "pierrot" end  factory.define(:rabbit) |f|   f.association :clown end 

you'd use them in test so:

describe rabbitscontroller    describe "get index"      "assigns rabbits"       @rabbit = factory(:rabbit)       :index       assigns[:rabbits].should == [@rabbit]           end   end end 

Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -