I want to create matcher that test whether a model is watched by observer.
I decided to dynamically add method after_create (if necessary), save instance of model and check is it true that observer instance received an after_create call. Simplified version (full version) :
RSpec::Matchers.define :be_observed_by do |observer_name|
match do |obj|
...
observer.class_eval do
define_method(:after_create) {}
end
observer.instance.should_receive(:after_create)
obj.save(validate: false)
...
begin
RSpec::Mocks::verify # run mock verifications
true
rescue RSpec::Mocks::MockExpectationError => e
# here one can use #{e} to construct an error message
false
end
end
end
It wasn't work. No instance of observer is received after_create call.
But If I modify actual code of Observer in app/models/user_observer.rb like this
class UserObserver
...
def after_create end
...
end
It works as expected.
What should I do to add after_create method dynamically to force trigger observer after create?
In short, this behavior is due to the fact that Rails hooks up UserObserver callbacks to User events at the initialization time. If the after_create callback is not defined for UserObserver at that time, it will not be called, even if later added.
If you are interested in more details on how that observer initialization and hook-up to the wobserved class works, at the end I posted a brief walk-through through the Observer implementation. But before we get to that, here is a way to make your tests work. Now, I'm not sure if you want to use that, and not sure why you decided to test the observer behavior in the first place in your application, but for the sake of completeness...
After you do define_method(:after_create) for observer in your matcher insert the explicit call to define_callbacks (a protected method; see walkthrough through the Observer implementatiin below on what it does) on observer instance. Here is the code:
observer.class_eval do
define_method(:after_create) { |user| }
end
observer.instance.instance_eval do # this is the added code
define_callbacks(obj.class) # - || -
end # - || -
A brief walk-through through the Observer implementation.
Note: I'm using the "rails-observers" gem sources (in Rails 4 observers were moved to an optional gem, which by default is not installed). In your case, if you are on Rails 3.x, the details of implementation may be different, but I believe the idea will be the same.
First, this is where the observers' instantiation is launched: https://github.com/rails/rails-observers/blob/master/lib/rails/observers/railtie.rb#L24. Basically, call ActiveRecord::Base.instantiate_observers in ActiveSupport.on_load(:active_record), i.e. when the ActiveRecord library is loaded.
In the same file you can see how it takes the config.active_record.observers parameter normally provided in the config/application.rb and passes it to the observers= defined here: https://github.com/rails/rails-observers/blob/master/lib/rails/observers/active_model/observing.rb#L38
But back to ActiveRecord::Base.instantiate_observers. It just cycles through all defined observers and calls instantiate_observer for each of them. Here is where the instantiate_observer is implemented: https://github.com/rails/rails-observers/blob/master/lib/rails/observers/active_model/observing.rb#L180. Basically, it makes a call to Observer.instance (as a Singleton, an observer has a single instance), which will initialize that instance if that was not done yet.
This is how Observer initialization looks like: https://github.com/rails/rails-observers/blob/master/lib/rails/observers/active_model/observing.rb#L340. I.e. a call to add_observer!.
You can see add_observer!, together with and define_callbacks that it calls, here: https://github.com/rails/rails-observers/blob/master/lib/rails/observers/activerecord/observer.rb#L95.
This define_callbacks method goes through all the callbacks defined in your observer class (UserObserver) at that time and creates "_notify_#{observer_name}_for_#{callback}" methods for the observed class (User), and register them to be called on that event in the observed class (User, again).
In your case, it should have been _notify_user_observer_for_after_create method added as after_create callback to User. Inside, that _notify_user_observer_for_after_create would call update on the UserObserver class, which in turn would call after_create on UserObserver, and all would work from there.
But, in your case after_create doesn't exist in UserObserver during Rails initialization, so no method is created and registered for User.after_create callback. Thus, no luck after that with catching it in your tests. That little mystery is solved.
Related
I have a private model method in my rails app that is so vital to quality of life as we know it that I want to test it using rspec so that it squawks if future tampering changes how it works.
class MyModel < ApplicationRecord
belongs_to something
has_many somethings
after_create :my_vital_method
validates :stuff
private
def my_vital_method
#do stuff
end
end
When I try calling the method in an rspec test I get the following error message:
NoMethodError: undefined method `my_vital_method' for #< Class:......>
Question: How do I call a private model method in rspec?
By definition, you are not allowed to call private methods from outside of the class because they are private.
Fortunately for you, you can do what you want if you use object.send(:my_vital_method) which skips the testing for method call restrictions.
Now, the bigger issue is that you really are making your object more brittle, because calling from outside like that may need implementation details that will get out of sync with the class over time. You are effectively increasing the Object API.
Finally, if you are trying to prevent tampering, then you are tilting at windmills -- you can't in Ruby because I can just trivially redefine your method and ensure that if my new method is called from your anti-tamper checking code, I call the original version, else I do my nefarious stuff.
Good luck.
If your private method needs testing it probably should be a public method of another class. If you find the name of this class define its purpose and then create the method signature you want you would end up with something like
def my_vital_method
MyVitalClass.new.do_stuff
end
and now you can write a spec for do_stuff.
I have a rails 4 app that has an alert model and tests associated to each alert.
When a new alert is created I have a an after_create filter that uses an instance method to create a new test:
class Alert < ActiveRecord::Base
has_many :tests
after_create :create_test
private
def create_test
#bunch of code using external api to get some data
Test.create
end
end
I also have a cron job that I want to use to create a new test for each alert. My plan was to have a class method to do that:
def self.scheduled_test_creation
#alerts = Alert.all
#alerts.each do |a|
a.create_test
end
end
That won't work because the instance method is private. I know I can get around this using send for example. Or I can make the methods public. Or I can rewrite that bunch of api code in the instance method.
I am just not sure what the best way would be. I don't want to write the same code twice and I want to make sure is good practice. Maybe in this case the methods don't have to be private - I know the difference between public/private/protected but I don't really understand when methods should be private/protected.
Any help would be greatly appreciated
I like service classes for interactions between multiple models. Callbacks can make the logic quite hard to follow.
Eg:
class AlertCreator
def initialize(alert)
#alert = alert
end
def call
if #alert.save
alert_test = TestBuilder.new(#alert).call
alert_test.save
true
end
end
end
class TestBuilder
def initialize(alert)
#alert = alert
end
def call
# external API interaction stuff
# return unsaved test
end
end
Inside your controller, you'd call AlertCreator.new(#alert).call instead of the usual #alert.save.
I agree with #SergioTulentsev: while in the long run you may be better served by breaking out this logic into a service class, in the short run you simply shouldn't make a method private if it needs to be called outside of the instance.
In some cases you actually want to access a private method, for example when verifying object state during tests. This is easy to do:
#alert.instance_eval{ create_test }
You can even fetch or alter instance variables this way:
#alert.instance_eval{ #has_code_smells = true }
In general, if you feel the need to do this, it's a warning smell that your logic needs to be rethunk. Ignoring that sort of smell is what turns Ruby from a wonderful language into a way-too-powerful language that allows you to shoot yourself in the foot. But it's doable.
I'm trying to implement a model auditor that looks for changes to the Mongo. Originally, I tried to make a base class that my models inherit from, but I found out that's not possible.
I'm adding a module to a model that relies on Mongoid. The module contains after_create, after_update, and after_destroy callbacks. And that's the problem... In order to get the callbacks to work as if they are class-level methods, I have to do something this.
module Auditor
def self.after_create
#after create code
end
end
However, I this will override any after create calls inside my model.
Is there a way I can modify my Auditor module's after_create method to accept what the model wants to run callbacks on?
I'd like to catch and remove method calls in my Rails models in certain cases.
I'd like something like the remove_method, but that removes method calls.
For example, if I have a before_save callback in a model, I may want to catch it using a module that's extended into the class, and remove or prevent the before_save from firing.
Is this possible?
Thanks.
Edit:
The pervious answer I posted does not work - not sure if it ever did, but I vaguely recall using in the past. To skip callbacks, in the context of a subclass, for example, you should use skip_callback. Example of the usage:
skip_callback :save, :before, :callback_method_name
Or if you want to skip callbacks under a for a particular condition:
skip_callback :save, :before, :callback_method_name, if: :some_condition_true?
There is also a reset_callbacks method that takes the callback type as a parameter. For example, reset_callbacks :save. The callbacks can be accessed via the class methods, _save_callbacks, _create_callbacks, etc. I would use caution when using reset_callbacks since it appears that Rails itself is defining callbacks for associations, namely, :before_save_collection_association.
If you're talking about just regular Ruby objects, you can override methods in subclasses. Just define a method with the same name as the superclass. You can also override base class methods in a subclass by including a module which defines the same instance methods as the base class.
Have you tried clearing before_save like this:
before_save ->{}
Preface: This is in the context of a Rails application. The question, however, is specific to Ruby.
Let's say I have a Media object.
class Media < ActiveRecord::Base
end
I've extended it in a few subclasses:
class Image < Media
def show
# logic
end
end
class Video < Media
def show
# logic
end
end
From within the Media class, I want to call the implementation of show from the proper subclass. So, from Media, if self is a Video, then it would call Video's show method. If self is instead an Image, it would call Image's show method.
Coming from a Java background, the first thing that popped into my head was 'create an abstract method in the superclass'. However, I've read in several places (including Stack Overflow) that abstract methods aren't the best way to deal with this in Ruby.
With that in mind, I started researching typecasting and discovered that this is also a relic of Java thinking that I need to banish from my mind when dealing with Ruby.
Defeated, I started coding something that looked like this:
def superclass_method
# logic
this_media = self.type.constantize.find(self.id)
this_media.show
end
I've been coding in Ruby/Rails for a while now, but since this was my first time trying out this behavior and existing resources didn't answer my question directly, I wanted to get feedback from more-seasoned developers on how to accomplish my task.
So, how can I call a subclass's implementation of a method from the superclass in Rails? Is there a better way than what I ended up (almost) implementing?
Good question, but you are making it too complicated. Keep in mind a few principles and it should all be clear...
The types will be resolved dynamically, so if a show exists anywhere in the object's class hierarchy at the moment it is actually called then Ruby will find it and call it. You are welcome to type in method calls to anything that may or may not exist in the future and it's legal ruby syntax and it will parse. You can type in an expression that includes a reference to this_will_never_be_implemented and no one will care unless it actually gets called.
Even in Java, there is only one actual object. Yes, you may have a method in the superclass that's calling a method, but it is an instance of the derived class (as well as an instance of the base class) and so you can count on the new show being called.
In a sense, every Ruby class is an abstract class containing stubs for every possible method that might be defined in the future. You can call anything without access qualifiers in the base class or derived class.
If you want a null superclass implementation, you may want to define one that does nothing or raises an exception.
Update: Possibly, I should have just said "call show like any other method" and left it at that, but having come this far I want to add: You can also implement show with Ruby's version of multiple inheritance: include SomeModule. Since you are obviously interested in Ruby's object model, you might implement your attribute with a mixin just for fun.
As you know having a superclass know about subclass functionality is a big no-no, which is why you wanted the abstract method.
What you want to do is define show in your superclass. Then you can call it in the superclass and the subclass will call its own version but the superclass won't throw an error.
class Media < ActiveRecord::Base
def show
# This method should be overloaded in a subclass
puts "Called from Media"
end
def do_something
show
end
end
class Image < Media
def show
puts "Called from Image"
end
end
class Video < Media
def show
puts "Called from Video"
end
end
i = Image.new
i.do_something
=> Called from Image
v = Video.new
v.do_something
=> Called from Video
Simple answer. Just call it. Ruby does not have compile-time checking so there is no one to complain that show isn't defined on Media. If #example is an instance of Image, then any call to #example.show will be sent to Image#show first, wherever it is made. Only if Image#show doesn't exist then the call will be passed on to Media, even if the call originated from code defined in Media
If you want to call show on self from within a method of Media, simply do it. However, make sure self responds to the method call.
class Media < ActiveRecord::Base
def foo
if self.respond_to?(:show)
self.show
else
... // *
end
end
...
end
To avoid the branch, implement show on Media, using the * as the body of show
class Media < ActiveRecord::Base
def foo
self.show
end
def show
...
end
end