Reputation: 2859
I have a model like this:
class Thing
class << self
def do_stuff(param)
result1 = method_one(param)
result2 = method_two(result1)
end
def method_one(param)
# tranformation
end
def method_two(result1)
# transformation
end
end
end
How can I test that do_stuff
is properly executing the methods of method_one
and method_two
with the right arguments? I have tried mock_model / mock_class but those don't make any sense to me. I have read the documentation but I'm still having a hard time making sense of it.
My test looks like this:
require 'rails_helper'
RSpec.describe Thing, type: :model do
let!(:param) { create(:param) }
describe '#do_stuff' do
thing = double('thing')
expect(thing).to receive(:method_one).with param
thing.do_stuff param
end
end
Why does this not work? The error I receive is that thing received an unexpected message param. But it was quite expected and that was the test. Where am I going wrong?
Upvotes: 0
Views: 144
Reputation: 2464
I think you shouldn't double your model. Following example works for me:
class Thing
class << self
def do_stuff(param)
result1 = method_one(param)
result2 = method_two(result1)
end
def method_one(param)
param[:foo]
end
def method_two(result1)
# transformation
result1
end
end
end
# thing_spec.rb
require 'rails_helper'
RSpec.describe Thing, type: :model do
let!(:param) { {foo: "bar"} }
describe '#do_stuff' do
it 'should do stuff' do
expect(Thing).to receive(:method_one).with(param)
Thing.do_stuff param
end
end
end
Test result
[retgoat@iMac-Roman ~/workspace/tapp]$ be rspec spec/models/thing_spec.rb
DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables serving everything in the `public` folder and is unrelated to the asset pipeline). The `serve_static_assets` alias will be removed in Rails 5.0. Please migrate your configuration files accordingly. (called from block in <top (required)> at /Users/retgoat/workspace/tapp/config/environments/test.rb:16)
.
Finished in 0.0069 seconds (files took 1.78 seconds to load)
1 example, 0 failures
Upvotes: 2