Ruby on rails 在Rails/RSpec请求测试中模拟非本地请求

Ruby on rails 在Rails/RSpec请求测试中模拟非本地请求,ruby-on-rails,rspec,Ruby On Rails,Rspec,我想阻止所有非本地请求者访问应用程序(我的应用程序的实际功能实际上更复杂,但弄清楚如何做到这一点将解决我的具体问题)。我将如何在RSpec中使用请求测试来测试它 在spec/requests/gatekeeper\u spec.rb describe "A local request to the site root" do before :each do get root_path end it "should not allow access" do respon

我想阻止所有非本地请求者访问应用程序(我的应用程序的实际功能实际上更复杂,但弄清楚如何做到这一点将解决我的具体问题)。我将如何在RSpec中使用请求测试来测试它

spec/requests/gatekeeper\u spec.rb

describe "A local request to the site root" do
  before :each do
    get root_path
  end
  it "should not allow access" do
    response.status.should be(401)
  end
end

describe "An external (terminology?) request to the site root" do
  before :all do
    # TODO: make request remote
  end
  before :each do
    get root_path
  end
  it "should allow access" do
    response.status.should be(200)
  end
end
我应该如何实现
#TODO
行?我已经研究过mock,并认为索具
请求。remote_ip
可能合适,但我不确定这种mock是如何实现的。

未经测试,但应该在Rails 2.3.x和3.0中工作:

before :each do
  Rails::Initializer.run do |config|
    config.action_controller.consider_all_requests_local = false
  end
end

after :each do
  Rails::Initializer.run do |config|
    config.action_controller.consider_all_requests_local = true
  end
end

如果我理解正确的话,测试请求的远程地址是“0.0.0.0”,因此它们通常被认为是远程的,您希望存根本地请求,而不是相反

我认为这应该适用于控制器规范——不确定请求规范:

request.stub(:local?) { true }

在Rails 4中,您可以使用:

RSpec.configure do |config|
  config.before(:each, allow_rescue: true) do
    Rails.application.config.action_dispatch.stub(:show_exceptions) { true }
    Rails.application.config.stub(:consider_all_requests_local) { false }
  end
end
然后在测试文件中:

describe "A test" do
  it "renders custom error pages", :allow_rescue => true do
    # ...
  end
end
名称
:allow_rescue
取自
ActionController::Base.allow_rescue
配置,该配置存在于Rails 3中,RSpec配置如下:

RSpec.configure do |config|
  config.before(:each, allow_rescue: true) do
    ActionController::Base.stub(:allow_rescue) { true }
  end
end

我不熟悉RubyonRails,但是应该“it”应该[不]允许访问吗?应该是“if…”?@Hello71:不用担心。RSpec很时髦<代码>它是正确的。这是Ruby世界中整个可读性趋势的一部分。在通过
get
发出请求之前,请求对象似乎不存在。我确实认为扩展这个函数是解决这个难题的最好办法。嗯,看起来请求规范是不同的。您也可以尝试
get root\u path,nil,“REMOTE\u ADDR”=>“127.0.0.1”
来模拟本地主机。stubing思想很好,我在我的控制器规范中有效地使用了它。我将“访问检查器”实现为\u filter之前的
,并将相应的过滤器存根为只返回
true
,而不是重定向。控制器规格允许我通过局部变量
Controller
访问控制器。至于请求规范,我无法实现它,但是函数已经改变了,所以希望这个缺口会被忽略,至少在Rails指南填补这个细节之前。