How to test model's callback method independently? - ruby-on-rails

I had a method in a model:
class Article < ActiveRecord::Base
def do_something
end
end
I also had a unit test for this method:
# spec/models/article_spec.rb
describe "#do_something" do
#article = FactoryGirl.create(:article)
it "should work as expected" do
#article.do_something
expect(#article).to have_something
end
# ...several other examples for different cases
end
Everything was fine until I found it's better to move this method into a after_save callback:
class Article < ActiveRecord::Base
after_save :do_something
def do_something
end
end
Now all my tests about this method broken. I have to fix it by:
No more specific call to do_something because create or save will trigger this method as well, or I'll meet duplicate db actions.
Change create to build
Test respond_to
Use general model.save instead of individual method call model.do_something
describe "#do_something" do
#article = FactoryGirl.build(:article)
it "should work as expected" do
expect{#article.save}.not_to raise_error
expect(#article).to have_something
expect(#article).to respond_to(:do_something)
end
end
The test passed but my concern is it's no longer about the specific method. The effect will be mixed with other callbacks if more added.
My question is, is there any beautiful way to test model's instance methods independently that becoming a callback?

Callback and Callback behavior are independent tests. If you want to check an after_save callback, you need to think of it as two things:
Is the callback being fired for the right events?
Is the called function doing the right thing?
Assume you have the Article class with many callbacks, this is how you would test:
class Article < ActiveRecord::Base
after_save :do_something
after_destroy :do_something_else
...
end
it "triggers do_something on save" do
expect(#article).to receive(:do_something)
#article.save
end
it "triggers do_something_else on destroy" do
expect(#article).to receive(:do_something_else)
#article.destroy
end
it "#do_something should work as expected" do
# Actual tests for do_something method
end
This decouples your callbacks from behavior. For example, you could trigger the same callback method article.do_something when some other related object is updated, say like user.before_save { user.article.do_something }. This will accomodate all those.
So, keep testing your methods as usual. Worry about the callbacks separately.
Edit: typos and potential misconceptions
Edit: change "do something" to "trigger something"

You can use shoulda-callback-matchers to test existence of your callbacks without calling them.
describe Article do
it { is_expected.to callback(:do_something).after(:save) }
end
If you also want to test the behaviour of the callback:
describe Article do
...
describe "#do_something" do
it "gives the article something" do
#article.save
expect(#article).to have_something
end
end
end

I like to use ActiveRecord #run_callbacks method to make sure callbacks are been called without need to hit database. This way it runs faster.
describe "#save" do
let(:article) { FactoryBot.build(:article) }
it "runs .do_something after save" do
expect(article).to receive(:do_something)
article.run_callbacks(:save)
end
end
And to test the behavior of #do_something you add another test specifically for that.
describe "#do_something" do
let(:article) { FactoryBot.build(:article) }
it "return thing" do
expect(article.do_something).to be_eq("thing")
end
end

In the spirit of Sandi Metz and minimalist testing, the suggestion in https://stackoverflow.com/a/16678194/2001785 to confirm the call to a possibly private method does not seem right to me.
Testing a publicly-observable side-effect or confirming an outgoing command message makes more sense to me. Christian Rolle provided an example at http://www.chrisrolle.com/en/blog/activerecord-callback-tests-with-rspec.

This is more of a comment than an answer, but I put it here for the syntax highlighting...
I wanted a way to skip the callbacks in my tests, this is what I did. (This might help with the tests that broke.)
class Article < ActiveRecord::Base
attr_accessor :save_without_callbacks
after_save :do_something
def do_something_in_db
unless self.save_without_callbacks
# do something here
end
end
end
# spec/models/article_spec.rb
describe Article do
context "after_save callback" do
[true,false].each do |save_without_callbacks|
context "with#{save_without_callbacks ? 'out' : nil} callbacks" do
let(:article) do
a = FactoryGirl.build(:article)
a.save_without_callbacks = save_without_callbacks
end
it do
if save_without_callbacks
# do something in db
else
# don't do something in db
end
end
end
end
end
end

describe "#do_something" do
it "gives the article something" do
#article = FactoryGirl.build(:article)
expect(#article).to have_something
#article.save
end
end

Related

Check if a method of a class is called from the method of the different class in rspec

Let's say there are two classes:
1.
class Fax
def initialize(number)
**code**
end
def send!
**code**
end
end
class FaxJob
def perform
Fax.new(number).send!
end
end
In the FaxJobSpec, I need to confirm that
FaxJob.perform_now(number) run the Fax.new(number).send!
You should use a double.
it 'sends fax!' do
fax_instance = instance_double(Fax)
allow(Fax).to(receive(:new).and_return(fax_instance))
allow(fax_instance).to(receive(:send!))
FaxJob.perform_now(number)
expect(fax_instance).to(have_received(:send!))
end
You can avoid having to allow instance and class with a minor refactor to your Fax class:
class Fax
def self.send!(number)
new(number).send!
end
end
FaxJob:
class FaxJob
def perform
Fax.send!(number)
end
end
And then your test:
it 'sends fax!' do
allow(Fax).to(receive(:send!).and_call_original)
FaxJob.perform_now(number)
expect(Fax).to(have_received(:send!).with(number))
end
If you are really into DRY, this should work too:
it 'sends fax!' do
expect(Fax).to(receive(:send!).with(number))
FaxJob.perform_now(number)
end
I am not really found of this latter one because it does not respect the AAA (arrange, act, assert) and it compromises readability, imo.

Minitest - How do you test a method isn't invoked?

I'm trying to check if a method isn't invoked within an after_update callback.
I'm currently doing:
class Foo
def self.call; end
end
def Model < ActiveRecord::Base
after_update :do_something
def do_something
return unless title_changed?
Foo.call
end
end
In the test it works like that:
test 'Foo.new.bar is invoked' do
mock = Minitest::mock.new
mock.expect :call, nil
Foo.stub(:call) { update_record_to_fire_callback }
mock.verify
end
And it beautifully pass, but now I'm trying to do the opposite but without luck as I don't know how to do it. If I do assert_not mock.verify Minitest complains anyway for the method to be executed.
Or maybe there are other way to check a method isn't invoked? The method will do an expensive request, so, I want to avoid that.
I'm using Rails 5 and sadly Minitest. I'm open to add any gem that can work with these versions.
Since you're open to adding a gem, mocha works well for this. Add the gem, then use mocha's Expectation#never. Your test can then look like:
test 'Foo.new.bar is not invoked' do
model = Model.new
Foo.expects(:call).never
model.update!(not_the_title: 'value')
end
The easiest way to accomplish this is to stub the method that you want to ensure isn't called and have it raise an error.
class ModelTest < ActiveSupport::TestCase
test "does not call Foo.call when title is not changed" do
model = Model.new
refute model.title_changed?
Foo.stub(:call, -> { raise "Foo was called!" }) do
model.title = "something new"
end
assert model.title_changed?
end
end
There is no assertion to check that an error was not explicitly raised. Rails does have assert_nothing_raised, but Minitest does not. You can add it if you like.
class ModelTest < ActiveSupport::TestCase
test "does not call Foo.call when title is not changed" do
model = Model.new
refute model.title_changed?
Foo.stub(:call, -> { raise "Foo was called!" }) do
assert_nothing_raised do
model.title = "something new"
end
end
assert model.title_changed?
end
end

Rspec how to set an expectation on the superclass for an overridden method

I've got a model class that overrides update_attributes:
class Foo < ActiveRecord::Base
def update_attributes(attributes)
if super(attributes)
#do some other cool stuff
end
end
end
I'm trying to figure out how to set an expectation and/or stub on the super version of update_attributes to make sure that in the success case the other stuff is done. Also I want to make sure that the super method is actually being called at all.
Here's what I have tried so far (and it didn't work, of course):
describe "#update_attributes override" do
it "calls the base class version" do
parameters = Factory.attributes_for(:foo)
foo = Factory(:foo, :title => "old title")
ActiveRecord::Base.should_receive(:update_attributes).once
foo.update_attributes(parameters)
end
end
This doesn't work, of course:
Failure/Error: ActiveRecord::Base.should_recieve(:update_attributes).once
NoMethodError:
undefined method `should_recieve' for ActiveRecord::Base:Class
Any ideas?
update_attributes is an instance method, not a class method, so you cannot stub it directly on ActiveRecord::Base with rspec-mocks, as far as I know. And I don't think that you should: the use of super is an implementation detail that you shouldn't be coupling your test to. Instead, its better to write examples that specify the behavior you want to achieve. What behavior do you get from using super that you wouldn't get if super wasn't used?
As an example, if this was the code:
class Foo < ActiveRecord::Base
def update_attributes(attributes)
if super(attributes)
MyMailer.deliver_notification_email
end
end
end
...then I think the interesting pertinent behavior is that the email is only delivered if there are no validation errors (since that will cause super to return true rather than false). So, I might spec this behavior like so:
describe Foo do
describe "#update_attributes" do
it 'sends an email when it passes validations' do
record = Foo.new
record.stub(:valid? => true)
MyMailer.should_receive(:deliver_notification_email)
record.update_attributes(:some => 'attribute')
end
it 'does not sent an email when it fails validations' do
record = Foo.new
record.stub(:valid? => false)
MyMailer.should_receive(:deliver_notification_email)
record.update_attributes(:some => 'attribute')
end
end
end
Try replacing should_recieve with should_receive.

Rspec2 testing a before_validation method

I have the following to remove the spaces on a specific attribute.
#before_validation :strip_whitespace
protected
def strip_whitespace
self.title = self.title.strip
end
And I want to test it. For now, I've tried:
it "shouldn't create a new part with title beggining with space" do
#part = Part.new(#attr.merge(:title => " Test"))
#part.title.should.eql?("Test")
end
What am I missing?
Validations won't run until the object is saved, or you invoke valid? manually. Your before_validation callback isn't being run in your current example because your validations are never checked. In your test I would suggest that you run #part.valid? before checking that the title is changed to what you expect it to be.
app/models/part.rb
class Part < ActiveRecord::Base
before_validation :strip_whitespace
protected
def strip_whitespace
self.title = self.title.strip
end
end
spec/models/part_spec.rb
require 'spec_helper'
describe Part do
it "should remove extra space when validated" do
part = Part.new(:title => " Test")
part.valid?
part.title.should == "Test"
end
end
This will pass when the validation is included, and fails when the validation is commented out.
referring to #danivovich example
class Part < ActiveRecord::Base
before_validation :strip_whitespace
protected
def strip_whitespace
self.title = self.title.strip
end
end
the proper way to write the spec is to separately write spec on strip_whitespace method and then just check if model class have callback set on it, like this:.
describe Part do
let(:record){ described_class.new }
it{ described_class._validation_callbacks.select{|cb| cb.kind.eql?(:before)}.collect(&:filter).should include(:strip_whitespace) }
#private methods
describe :strip_whitespace do
subject{ record.send(:strip_whitespace)} # I'm using send() because calling private method
before{ record.stub(:title).and_return(' foo ')
it "should strip white spaces" do
subject.should eq 'foo'
# or even shorter
should eq 'foo'
end
end
end
if you need to skip callback behavior in some scenarios use
before{ Part.skip_callback(:validation, :before, :strip_whitespace)}
before{ Part.set_callback( :validation, :before, :strip_whitespace)}
Update 20.01.2013
BTW I wrote a gem with RSpec matchers to test this https://github.com/equivalent/shoulda-matchers-callbacks
In general I don't recommend callback at all. They are fine for example in this question, however once you do more complicated stuff like:
After create->
link account to user
create notification
send email to Admin
...then you should create custom service object to deal with this and test them separately.
http://railscasts.com/episodes/398-service-objects
http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

How are both of these tests passing?

I'm using Shoulda, Mocha, and Test::Unit for testing. I have the following controller and test:
class FoosController < ApplicationController
caches_action :show
def show
#foo = requested_foo
end
private
def requested_foo
Foo.find(params[:id])
end
end
class FoosCachingTest < ActionController::IntegrationTest
def setup
#foo = Foo.first
#session = open_session
end
context 'FoosController#show' do
setup do
#session.get('/foos/1')
end
before_should 'not fetch the Foo from the database' do
FoosController.any_instance.expects(:requested_foo).never
end
before_should 'fetch the Foo from the database' do
FoosController.any_instance.expects(:requested_foo).once.returns(#foo)
end
end
end
How is it that both of those tests could pass? I am not explicitly expiring my mocks at any point. Are Mohca and Shoulda known to interact poorly in this regard?
Aha! The problem is that the expectations do indeed fail but the errors they throw are swallowed up by the controller's error handling. Testing that the action renders properly makes the proper test fail.

Resources