WebMock:Rspec – 使用JSON响应测试Facebookvalidation

我很难为我的程序编写规范,因为我需要在填写所有正确的格式信息后validationfacebook ID。 我的facebook ID是从JSON响应中检索的,所以我不知道如何在我的规范中描述它。 我对这个领域很陌生,而且我已经被困在这一点很长一段时间了。 如果有一些示例代码可以帮助我,我将不胜感激。 以下是我的半成品规格。

场景:如果用户名和fbid相同,则使用用户给定的Fbid通过使用“ http://graph.facebook.com ”(JSON响应)来validationFacebook页面。

我的githuburl: 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!(:allow =>“ 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 

结束

您正在对HTTPS请求进行存根,但使用端口443执行HTTP,这就是为什么Webmock找不到正确的存根。 读取使用Net :: HTTP.get获取https URL