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