How can I test if MyModel.all is called ?
The following code doesn't work as I expect it:
class MyClass
def call
cached_records
end
private
def cached_records
Rails.cache.fetch(self.class.name.underscore) do
MyModel.all
end
end
end
RSpec.describe MyClass do
subject { MyClass.new }
describe '#call' do
it 'only queries the database the first time' do
expect(MyModel).to receive(:all).once
MyClass.call
MyClass.call
end
end
end
Apparently I found the answer by tweaking the expectation.
expect(MyModel).to receive(:all).once.and_call_original
Why do I need to specify to call the original method ?
Related
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.
In my Order model I include a PORO class "ShipmentHandler". This PORO is located like this: app/models/order/shipment_handler.rb
I invoke this in my Order model like so:
def assign_shipments
ShipmentHandler.new(self).assign_shipments
end
My PORO looks like:
class Order
class ShipmentHandler
def initialize(order)
#set_some_variables
end
def some_methods
end
end
end
I'm trying to create spec to test the methods in my ShipmentHandler class. I'm not sure how to do this as I keep getting errors like uninitialized constant ShipmentHandler
I've tried to add it to my order_spec.rb like so:
describe Order do
describe Order::ShipmentHandler do
end
end
and:
describe Order do
describe ShipmentHandler do
end
end
Neither work. I've also tried creating a spec in spec/models/order/shipment_handler_spec.rb
This also failed.
The following way of writing specs worked for me when I made some assumptions on what your Order class looks like with the nested ShipmentHandler class:
class Order
def assign_shipments
ShipmentHandler.new(self).assign_shipments
end
class ShipmentHandler
def initialize(order)
#order = order
end
def some_methods
end
end
end
RSpec.describe Order do
it { is_expected.to be_a Order }
end
# Method 1
RSpec.describe Order::ShipmentHandler do
subject(:shipment_handler) { described_class.new(Order.new) }
it { is_expected.to be_a Order::ShipmentHandler }
end
# Method 2
class Order
RSpec.describe ShipmentHandler do
subject(:shipment_handler) { described_class.new(Order.new) }
it { is_expected.to be_a Order::ShipmentHandler }
end
end
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
class TestController < AplicationController
#....
private
def some_method
unless #my_variable.nil?
#...
return true
end
end
end
I want to test some_method directly in controller spec:
require 'spec_helper'
describe TestController do
it "test some_method"
phone = Phone.new(...)
controller.assign(:my_variable,phone) #does not work
controller.send(:some_method).should be_true
end
end
How I can set TestController instance variable #my_variable from controller spec?
When testing private methods in controllers, rather than use send, I tend to use an anonymous controller due to not wanting to call the private method directly, but the interface to the private method (or, in the test below, effectively stubbing that interface). So, in your case, perhaps something like:
require 'spec_helper'
describe TestController do
controller do
def test_some_method
some_method
end
end
describe "a phone test with some_method" do
subject { controller.test_some_method }
context "when my_variable is not nil" do
before { controller.instance_variable_set(:#my_variable, Phone.new(...)) }
it { should be_true }
end
context "when my_variable is nil" do
before { controller.instance_variable_set(:#my_variable, nil) }
it { should_not be_true } # or should be_false or whatever
end
end
end
There's some good discussion on the issue of directly testing private methods in this StackOverflow Q&A, which swayed me towards using anonymous controllers, but your opinion may differ.
instance_eval is a relatively clean way to accomplish this:
describe TestController do
it "test some_method" do
phone = Phone.new(...)
controller.instance_eval do
#my_variable = phone
end
controller.send(:some_method).should be_true
end
end
In this case, using do...end on instance_eval is overkill, and those three lines can be shortened to:
controller.instance_eval {#my_variable = phone}
I don't think you want to access an instance variable from your spec controller, as the spec should test the behaviour, but you can always stub the private method.
In your case it should be something like this (in this example it doesn't make so much sense):
describe TestController do
it "test some_method"
phone = Phone.new(...)
controller.stub(:some_method).and_return(true)
controller.send(:some_method).should be_true
end
end
If this is not what you are looking for take a look at this: How to set private instance variable used within a method test?
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.