我正在使用twitter gem編寫一個測試應用程序,我想編寫一個集成測試,但我無法弄清楚如何模擬Twitter命名空間中的對象。下面是我想測試功能:在ruby中模擬第三方對象的最佳方法是什麼?
def build_twitter(omniauth)
Twitter.configure do |config|
config.consumer_key = TWITTER_KEY
config.consumer_secret = TWITTER_SECRET
config.oauth_token = omniauth['credentials']['token']
config.oauth_token_secret = omniauth['credentials']['secret']
end
client = Twitter::Client.new
user = client.current_user
self.name = user.name
end
和這裏的,我試圖寫RSpec的測試:
feature 'testing oauth' do
before(:each) do
@twitter = double("Twitter")
@twitter.stub!(:configure).and_return true
@client = double("Twitter::Client")
@client.stub!(:current_user).and_return(@user)
@user = double("Twitter::User")
@user.stub!(:name).and_return("Tester")
end
scenario 'twitter' do
visit root_path
login_with_oauth
page.should have_content("Pages#home")
end
end
但是,我得到這個錯誤:
1) testing oauth twitter
Failure/Error: login_with_oauth
Twitter::Error::Unauthorized:
GET https://api.twitter.com/1/account/verify_credentials.json: 401: Invalid/expired Token
# ./app/models/user.rb:40:in `build_twitter'
# ./app/models/user.rb:16:in `build_authentication'
# ./app/controllers/authentications_controller.rb:47:in `create'
# ./spec/support/integration_spec_helper.rb:3:in `login_with_oauth'
# ./spec/integration/twit_test.rb:16:in `block (2 levels) in <top (required)>'
上面的模擬使用rspec,但我也願意嘗試摩卡。任何幫助將不勝感激。
好的,我得到了大家的幫助,得出了這個結論。下面是最終測試:
feature 'testing oauth' do
before(:each) do
@client = double("Twitter::Client")
@user = double("Twitter::User")
Twitter.stub!(:configure).and_return true
Twitter::Client.stub!(:new).and_return(@client)
@client.stub!(:current_user).and_return(@user)
@user.stub!(:name).and_return("Tester")
end
scenario 'twitter' do
visit root_path
login_with_oauth
page.should have_content("Pages#home")
end
end
訣竅是搞清楚,我需要存根上的實物:configure
和:new
並在dobuled對象實例存根:current_user
和:name
。
是的!謝謝。你完全正確,我錯過了在模型上對方法進行存根與對已加倍的實例進行存根之間的區別。多虧了這個,我才弄明白了。我會編輯這個問題,包括我最終如何解決這個問題。 – spinlock