0

I added to me application country separated content. Country sets up from IP address by subdomain in application.

before_action :check_domain

def check_domain
    redirect_to(subdomain: current_country.slug) unless Country.find_by(slug: request.subdomain)
  end

I have been added this for my application_controller to redirect users for right country from their IP addresess(if url has no subdomains already). In works fine, but a lot of my specs fault because of it(without redirecting every spec passed). For example spec:

require "rails_helper"

describe "Update user's preferred subjects", type: :request do
  let!(:video) { create(:video, :with_tags, tags: ["math"]) }
  let!(:related_video) { create(:video, :with_tags, tags: ["math"], subject: video.subject) }
  let!(:related_survey) { create(:survey, :with_tags, tags: ["math"], subject: video.subject) }

  it "responds with related materials" do
    get("/videos/#{video.id}/related_materials.json")

    expect(response_body.keys).to match_array(%w(videos offline_materials surveys meta))
    expect(response_body).to eq_serialized(
      RelatedMaterialsQuery.new(video, {}),
      serializer: RelatedMaterialsSerializer
    )
  end
end

I've got an error:

JSON::ParserError:
       784: unexpected token at '<html><body>You are being <a href="http://guyana-1.example.com/videos/1/related_materials">redirected</a>.</body></html>'

What should I change in rspec to pass it? It tried to parse html instead of json because of redirecting to country subdomain. How should I solve it? Thanks.

Damir Nurgaliev
  • 341
  • 5
  • 19

2 Answers2

1

Using follow_redirect! after a request should fix the problem.

describe "Update user's preferred subjects", type: :request do
  let!(:video) { create(:video, :with_tags, tags: ["math"]) }
  let!(:related_video) { create(:video, :with_tags, tags: ["math"], subject: video.subject) }
  let!(:related_survey) { create(:survey, :with_tags, tags: ["math"], subject: video.subject) }

  before do
    get("/videos/#{video.id}/related_materials.json")
    follow_redirect!
  end

  it "responds with related materials" do
    expect(response_body.keys).to match_array(%w(videos offline_materials surveys meta))
    expect(response_body).to eq_serialized(
      RelatedMaterialsQuery.new(video, {}),
      serializer: RelatedMaterialsSerializer
    )
  end
end

But I'd suggest testing once that the requests are redirected to the correct domain if there is no country. And in all other tests pre-create a Country to escape redirect or simply stub the check_domain method.

Igor Drozdov
  • 14,690
  • 5
  • 37
  • 53
0

You could modify your request.host manually to avoid redirects.

Alexander
  • 137
  • 1
  • 9