[mocha-developer] Stubbing ActiveRecord Models gets very difficult with instance methods

John Pywtorak jpywtora at calpoly.edu
Thu Jan 4 22:11:05 EST 2007


Francois Beausoleil wrote:
> Hello John,
> 
> 2007/1/3, John Pywtorak <jpywtora at calpoly.edu>:
>> Second try with minor correction, doh!
>> require 'test/unit'
>> require 'date'
>> require 'fear'
>> class ModelsTest < Test::Unit::TestCase
>>     attr :stat
>>
>>     def setup
>>       @stat = stub(:table_name => "P_TB", :maint_dt => Date.today,
>> :maint_time => "00:00")
>>     end
>>
>>     def test_check
>>       StatsTb.stubs(:find_by_table_name).returns(stat)
>>       StatsTb.find_stats.each { |st| assert st.check_stat }
>>     end
>> end
>>
>> So, this does not work, because the blocks st object is not an instance
>> a real instance with a check method and I can't stub check, because it
>> is the method under test.
> 
> What's wrong with doing this:
> 
> def test_check
>   @stat = StatTb.new
>   @stat.stubs(:maint_dt).returns(Date.today)
>   @stat.stubs(:maint_time).returns("00:00")
>   assert @stat.check_stat
> end
> 
> Or even:
> 
> def test_check
>   @stat = StatTb.new(:maint_dt => Date.today, :maint_time => "00:00")
>   assert @stat.check_stat
> end
> 
> There is not even any need to stub anything in the second version.
> You'll get one DB hit, to get the columns, but after that, it should
> be connection free.
> 
> I hope I understood your problem correctly.
> 
> Bye !

Yes, thanks I think that can work.  I had kind off locked myself into 
the dynamic magic nature of activerecord and wanted to avoid anything 
that newer versions of activerecord might break, or running into scaling 
issues as my example is very much a simple case.  I see that Jay Fields 
blog about this in much detail, so I am off the read his posts.  Thanks 
again.

John
http://ruby-talk.blogspot.com



More information about the mocha-developer mailing list