Simulating a non-local request in testing Rails / RSpec requests

I would like to block access to the application for all non-local requests (the actual functionality of my application is more complicated in practice, but figuring out how to do this will solve my specific problem). How can I verify this using query tests in RSpec?

AT 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 do I implement a string # TODO? I looked at the ridicule and thought that falsification request.remote_ipmight be appropriate, but I don’t know exactly how such a layout is implemented.

+3
source share
3 answers

If I understand correctly, test requests have a remote address of "0.0.0.0", so they are usually considered remote, and you want to stub local requests, and not vice versa.

, - :

request.stub(:local?) { true }
+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
+2

In Rails 4, you can do this with

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 the test file:

describe "A test" do
  it "renders custom error pages", :allow_rescue => true do
    # ...
  end
end

The name :allow_rescueis taken from the configuration ActionController::Base.allow_rescuethat exists in Rails 3 , and there the RSpec configuration will be:

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

Source: https://habr.com/ru/post/1783475/


All Articles