[英]Simulating a non-local request in Rails/RSpec request testing
I'd like to block off access to the application to all non-local requesters (my application's actual functionality in practice is more sophisticated, but figuring out how to do this will solve my specific issue). 我想阻止对所有非本地请求者的应用程序访问(我的应用程序在实践中的实际功能更复杂,但弄清楚如何执行此操作将解决我的具体问题)。 How would I go about testing this with request tests in RSpec?
我将如何在RSpec中进行请求测试?
In spec/requests/gatekeeper_spec.rb
在
spec/requests/gatekeeper_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
How should I implement the # TODO
line? 我该如何实现
# TODO
线? I've looked into mocks and think that rigging request.remote_ip
may be appropriate, but I'm not certain exactly how such a mock is implemented. 我已经研究了模拟并认为绑定
request.remote_ip
可能是合适的,但我不确定这样的模拟是如何实现的。
Untested, but should work in Rails 2.3.x and 3.0: 未经测试,但应该在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
If I understand correctly, test requests have a remote address of "0.0.0.0", so they would normally be considered remote and you'd want to stub the local requests, not the other way around. 如果我理解正确,测试请求的远程地址为“0.0.0.0”,因此它们通常被认为是远程的,你想要存根本地请求,而不是相反。
I think this should work for controller specs -- not sure about request specs: 我认为这应该适用于控制器规格 - 不确定请求规格:
request.stub(:local?) { true }
In Rails 4 you can do it with: 在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
And then in your test file: 然后在你的测试文件中:
describe "A test" do
it "renders custom error pages", :allow_rescue => true do
# ...
end
end
The name :allow_rescue
is taken from a ActionController::Base.allow_rescue
configuration which exists in Rails 3 , and there the RSpec configuration would be: 名称
:allow_rescue
取自Rails 3中存在的ActionController::Base.allow_rescue
配置,RSpec配置将是:
RSpec.configure do |config|
config.before(:each, allow_rescue: true) do
ActionController::Base.stub(:allow_rescue) { true }
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.