Reputation: 163
I have a controller action I want to test:
LOG = ApiRequest::Resource::Login
def create
@response = LOG.new(current_user, params: params).create
return if request_failed?
...
end
def request_failed?
if @response.is_a? Hash
false
else
error = @response
redirect_to new_login_path, alert: error
true
end
end
LOG.new(current_user, params: params).create
is an external api call that normally returns either a hash or a string with the error. I want to test the controller action without triggering the call, like force @response = {}
and check if it doesn't redirect and force @response = ""
which should trigger a redirect.
it 'redirects if fails the request' do
post :create
expect(response).to redirect_to new_login_path
expect(flash[:alert]).not_to be nil
end
How can you stub an instance variable?
Upvotes: 1
Views: 813
Reputation: 13477
I would test it with stubbing LOG
instance, something like:
let(:log_instance) { instance_double(LOG) }
before do
allow(LOG).to receive(:new).and_return(log_instance)
allow(log_instance).to receive(:create).and_return({})
end
Upvotes: 2