2013-07-20 48 views
3

我有困難爲我的程序編寫規格,因爲我需要在填寫所有正確格式信息後驗證facebook ID。我的Facebook ID是從JSON響應中檢索的,所以我不確定如何在我的規範中描述此內容。我對這個領域非常陌生,在這一點上我一直陷入困境。如果有一些示例代碼可以幫助我,我將不勝感激。以下是我的一半完成規格。WebMock:Rspec - 通過使用JSON響應測試Facebook驗證

場景:如果用戶名和fbid相同,則使用給定Fbid的用戶使用「http://graph.facebook.com」(JSON響應)驗證Facebook頁面是否匹配。

我github上網址:https://github.com/amycheong/company_list

更新:我已經使用WebMock但最終得到:

1) Companies new company create with valid information correct facebook id should validate fbid 
Failure/Error: Company.validate_fbid('pepsi')['username'].should == "pepsi" 
WebMock::NetConnectNotAllowedError: 
    Real HTTP connections are disabled. Unregistered request: GET http://graph.facebook.com:443/pepsi with headers {'Accept'=>'*/*', 'User-Agent'=>'Ruby'} 

    You can stub this request with the following snippet: 

    stub_request(:get, "http://graph.facebook.com:443/pepsi"). 
    with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}). 
    to_return(:status => 200, :body => "", :headers => {}) 

    registered request stubs: 

    stub_request(:get, "https://graph.facebook.com/pepsi") 

    ============================================================ 

我用了WebMock.disable_net_connect(:允許=> 「https://graph.facebook.com/」),但問題依然繼續。

模型文件:

def self.validate_fbid(fbid, format = :json) 
    uri = URI.parse("https://graph.facebook.com/#{fbid}") 
    data = Net::HTTP.get(uri) 
    return JSON.parse(data['username'])   
end 

SPEC文件:

before(:each) do 
     stub_request(:get, "https://graph.facebook.com/pepsi").to_return(:body => { 'username' => 'pepsi'}) 
    end 

    describe "correct facebook id" do    
     #validate fbid 
     it "should validate fbid" do    

      Company.validate_fbid('pepsi')['username'].should == "pepsi" 
      WebMock.should have_requested(:get, "https://graph.facebook.com/pepsi") 
     end 

    end 

控制器:

def create 
@company = Company.new(params[:company]) 

uri = URI("http://graph.facebook.com/" + @company.fbid) 
data = Net::HTTP.get(uri) 
username = JSON.parse(data)['username'] 
if !username.nil? 
    if @company.name.downcase == username.downcase 
     if @company.save 
      @message = "New company created" 
      redirect_to root_path 
     else 
      @message = "Company create attempt failed. Please try again." 
      render 'new' 
     end 
    else 
     @message = "Invalid facebook id" 
     render 'new' 
    end 
else 
    @message = "No such facebook id" 
    render 'new'    
end    

+1

'if!username.nil? '=>'如果用戶名' – apneadiving

+2

你應該使用類似webmock的模擬http呼叫 – apneadiving

+1

或錄像機:https://github.com/vcr/vcr – Nobita

回答

相關問題