您的位置:首页 > 编程语言 > Ruby

how to test observe with rspec in ruby on rails.

2011-01-01 16:38 519 查看
在测试 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.

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

测试代码

require 'spec_helper'

describe ContactInfoObserver do
before(:each) do
@phone = "15812345678"
@obs = ContactInfoObserver.instance
end

it ' should be change contact my user id when contact registered' do
user = mock_model(UserInfo)
UserInfo.stub(:find_by_phone).and_return(user)
m = mock_model(ContactInfo, :phone => @phone)
m.should_receive("my_user_id=").with(user.id)
@obs.before_create m
end

it ' should not change contact my user id when contact unregistered' do
UserInfo.stub(:find_by_phone).and_return(false)
m = mock_model(ContactInfo, :phone => @phone)
m.should_not_receive("my_user_id=")
@obs.before_create m
end

end


observer

class ContactInfoObserver < ActiveRecord::Observer
def before_create(contact_info)
#contact_info.logger.error("model "+contact_info.inspect)
user = UserInfo.find_by_phone contact_info.phone
puts "model observer"+user.inspect
if user
puts 'at here'
contact_info.my_user_id= user.id
end
end
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: