How to test observe with rspec in Ruby on Rails.

Source: Internet
Author: User
Tags ruby on rails

When testing the model, one change was observe. I wanted to test it, but the observer refused to execute it in rspec, but there was no problem with test env in the console.

It took me a day to debug and finally failed to solve the problem. If you encounter such problems, please help me. Thank you.

I used my spam English to ask on the rails mail list and asked me to read the following stuff.

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

We recommend that you test the observer and model separately and use mock to build the model in the Observer.

I tried to write it and thought it was good. record it.

 

TestCode

  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 ' Shocould 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 ' Shocould 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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.