So I have this simple ruby class:
class GetRequestList
def initialize(current_user, filter_hash)
@authorizer = RequestAuthorizer.new(current_user)
@filter = RequestFilter.new(filter_hash)
end
def generate
Request.send_chain(@authorizer.method_chain)
.send_chain(@filter.method_chain)
end
end
And I want to test that Request
receives two send_chain
methods in isolation of RequestAuthorizer
and RequestFilter
implementations. To do that I'm trying to use some stubs:
require 'test_helper'
class GetRequestListTest < ActiveSupport::TestCase
test "request should be filtered by filter and role" do
Request.expects(:send_chain).twice.returns([build(:request)])
RequestFilter.stubs(:new)
RequestFilter.any_instance.stubs(:method_chain).returns([])
RequestAuthorizer.stubs(:new)
RequestAuthorizer.any_instance.stubs(:method_chain).returns([])
assert GetRequestList.new(:current_user, :filter).generate.size == 1
end
end
You see what is wrong. stubs(:new)
returns nil
and there is no instances of RequestAuthorizer
and RequestFilter
in instance variables of GetRequestList
and we get an error. I can't figure out how to stub methods on instance variables.
Any suggestions?
Instead of stubbing out new
to return no value, have it return something e.g.
mock_request_filter = mock()
RequestFilter.stubs(:new).returns(mock_filter)
This also enables you to get read of the stubs on any_instance
- just set them on mock_request_filter
instead.