1
我試圖測試MailChimp訂閱的具體名單:存根MailChimp API調用功能測試
測試/功能/ 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
控制器/ 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
但我認爲我在這裏錯過了一些東西,因爲測試正在通過,但他們正在對API進行調用,因爲當我使用我的電子郵件進行測試時,我收到電子郵件確認從MailChimp每一次通貨膨脹,我跑:
"rake test:functionals"
如果我嘗試運行:
Gibbon.any_instance.stubs(:subscribe).raises(Gibbon::MailChimpError, 500)
或
Gibbon.any_instance.stubs(:subscribe).returns(200)
我收到以下錯誤:
test_invalid_signup(SomeControllerTest):
NoMethodError: undefined method 'any_instance' for Gibbon:Module
test_valid_signup(SomeControllerTest):
NoMethodError: undefined method 'any_instance' for Gibbon:Module
編輯I
我能夠使用any_instance方法這樣做:
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
但還是這樣做是對API的調用。
嗨@newmediafreak,我試過你的答案,但我得到了這個錯誤:test_valid_signup(SomeControllerTest): ActiveSupport :: JSON :: Encoding :: CircularReferenceError:對象引用自身。我在尋找原因。 – nisevi
閱讀本文後:github.com/rspec/rspec-mocks/issues/78我做了一些更改Gibbon :: API.any_instance.stubs({:EMAIL =>「[email protected]」})。returns(lists)但我仍然觸及MailChimp API,這就是我想要避免的......對不起,MailChimp API的答案中的延遲使我認爲他的答案是正確的...... – nisevi