我很难为我的程序编写规范,因为我需要在填写所有正确的格式信息后验证 Facebook ID。我的 facebook ID 是从 JSON 响应中检索到的,所以我不确定如何在我的规范中描述这一点。我对这个领域很陌生,我已经被困在这一点很长时间了。如果有一些示例代码可以帮助我,我将不胜感激。以下是我的半成品规格。
场景:如果用户名和 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!(: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
控制器 :
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
结尾