gpt4 book ai didi

ruby-on-rails - 网络模拟 : Rspec - Test Facebook Validation by using JSON response

转载 作者:行者123 更新时间:2023-12-04 05:42:56 26 4
gpt4 key购买 nike

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

场景:使用给定 Fbid 的用户通过使用“http://graph.facebook.com”(JSON 响应)匹配用户名和 fbid 来验证 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!(: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

规范文件:
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

Controller :
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

结尾

最佳答案

您正在 stub HTTPS 请求,但使用端口 443 执行 HTTP,这就是 Webmock 找不到正确 stub 的原因。
阅读 Using Net::HTTP.get for an https url

关于ruby-on-rails - 网络模拟 : Rspec - Test Facebook Validation by using JSON response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17760255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com