how to test observe with rspec in ruby on rails.

在测试 model时,有一个改动是observe, 我想一把测试了,可是这个observer在rspec中一直不肯执行. 但在console下的test env没有任何问题。

哥花了一天的时间来调试,终于还是没有搞定,有遇到此类的问题的朋友可以协助我一下,谢谢。

用我的垃圾英语在rails的mail list上问了一下,说要我看下面的东东

http://stackoverflow.com/questions/33048/how-would-you-test-observers-with-rspec-in-a-ruby-on-rails-application

上面主要还是推荐observer和model分开来测试,在observer中model的构建用mock.

试着写了一下,觉得还不错,记录一下。

 

测试代码

  
    
1 require ' spec_helper '
2
3 describe ContactInfoObserver do
4 before(:each) do
5 @phone = " 15812345678 "
6 @obs = ContactInfoObserver.instance
7 end
8
9 it ' should be change contact my user id when contact registered ' do
10 user = mock_model(UserInfo)
11 UserInfo.stub(:find_by_phone).and_return(user)
12 m = mock_model(ContactInfo, :phone => @phone)
13 m.should_receive( " my_user_id= " ).with(user.id)
14 @obs.before_create m
15 end
16
17 it ' should not change contact my user id when contact unregistered ' do
18 UserInfo.stub(:find_by_phone).and_return( false )
19 m = mock_model(ContactInfo, :phone => @phone)
20 m.should_not_receive( " my_user_id= " )
21 @obs.before_create m
22 end
23
24 end

 

observer

  
    
1 class ContactInfoObserver < ActiveRecord::Observer
2 def before_create(contact_info)
3 #contact_info.logger.error( " model " + contact_info.inspect)
4 user = UserInfo.find_by_phone contact_info.phone
5 puts " model observer " + user.inspect
6 if user
7 puts ' at here '
8 contact_info.my_user_id = user.id
9 end
10 end
11 end

 

你可能感兴趣的:(ruby on rails)