ruby on rails - Testing has_many association with RSpec -
i'm trying test hour model rspec, namely class method 'find_days_with_no_hours' behaves scope. business has_many hours associated through sti. find_days_with_no_hours needs called through business object , can't figure out how set in rspec test. want able test like:
bh = @business.hours.find_days_with_no_hours bh.length.should == 2
i've tried various approaches, creating business object (with, say, business.create), setting @business.hours << mock_model(businesshour, ..., ..., ...) doesn't work.
how done?
class business < activerecord::base has_many :hours, :as => :hourable end class hour < activerecord::base belongs_to :hourable, :polymorphic => true def self.find_days_with_no_hours where("start_time null") end end
you can't test arel method creating object via mocks. arel going go straight database, , not see mocks or you've created in memory. grab factory_girl , define hour factory yourself:
factory.define :hour |f| f.start_time {time.now} end factory.define :unstarted_day, :parent => :hour |f| f.start_time nil end
and in test...
business = factory.create(:business) business.hours << factory.create(:unstarted_day) bh = business.hours.find_days_with_no_hours bh.length.should == 1
however, factory_girl personal preference setting known state, can use create
statements or fixtures, problem trying use mock_model() (which prevents database hit), , using method queries database.
Comments
Post a Comment