I'm trying to test a MailChimp subscription to an specific list:
test/functional/some_controller_test.rb
require 'test_helper'
class SomeControllerTest < ActionController::TestCase
test "invalid signup" do
Gibbon.stubs(:subscribe).raises(Gibbon::MailChimpError, 500)
post :signup, {:EMAIL => "invalid_email"}
assert_response 500
end
test "valid signup" do
Gibbon.stubs(:subscribe).returns(200)
post :signup, {:EMAIL => "[email protected]"}
assert_response 200
end
end
controllers/some_controller.rb
class SomeController < ApplicationController
def signup
begin
gb = Gibbon::API.new
resp = gb.lists.subscribe(
:id => ENV["key_list"],
:email => {:email => "#{params[:EMAIL]}"}
)
render :status => :ok, :json => resp
rescue Gibbon::MailChimpError => e
render :status => :internal_server_error, :json => {error: e, message: e.message}
end
end
end
But I think that I missing something here because the tests are passing but they are doing a call to the API, because as I'm using my email for testing purposes I receive the email confirmation from MailChimp each time that I run:
"rake test:functionals"
And if I try to run:
Gibbon.any_instance.stubs(:subscribe).raises(Gibbon::MailChimpError, 500)
or
Gibbon.any_instance.stubs(:subscribe).returns(200)
I get the following errors:
test_invalid_signup(SomeControllerTest):
NoMethodError: undefined method 'any_instance' for Gibbon:Module
test_valid_signup(SomeControllerTest):
NoMethodError: undefined method 'any_instance' for Gibbon:Module
EDIT I
I was able to use any_instance method doing this:
require 'test_helper'
class NewsletterControllerTest < ActionController::TestCase
test "invalid signup" do
gb = Gibbon::API.new
gb.any_instance.stubs(:subscribe).raises(Gibbon::MailChimpError, 500)
post :signup, {:EMAIL => "invalid_email"}
assert_response 500
end
test "valid signup" do
gb = Gibbon::API.new
gb.any_instance.stubs(:subscribe).returns(200)
post :signup, {:EMAIL => "[email protected]"}
assert_response 200
end
end
But still is doing a call to the API.
I'm used to RSpec (not TestUnit/Mocha), so I'm not all too familiar with the correct syntax here.
However, I do notice that you need to stub
any_instance
ofGibbon::API
, so I'm guessingGibbon::API.any_instance
is what you need at least. Besides that, you'll need to stub both thelists
as well as thesubscribe
method.So, I'm guessing something like this should work in your
valid signup
test case:I don't think you'll have to return
200
, since that's what the render does.