我想阻止对所有非本地请求者的应用程序访问(我的应用程序在实践中的实际功能更复杂,但弄清楚如何执行此操作将解决我的具体问题)。我将如何使用RSpec中的请求测试进行测试?
在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
我应该如何实施# TODO
行?我已经研究过模拟并认为绑定request.remote_ip
可能是合适的,但我不确定如何实现这样的模拟。
答案 0 :(得分:2)
未经测试,但应该在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
答案 1 :(得分:2)
如果我理解正确,测试请求的远程地址为“0.0.0.0”,因此它们通常被认为是远程的,你想要存根本地请求,而不是相反。
我认为这应该适用于控制器规范 - 不确定请求规范:
request.stub(:local?) { true }
答案 2 :(得分:1)
在 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
取自 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