Nice programing

Rails rspec 세트 하위 도메인

nicepro 2020. 12. 28. 22:34
반응형

Rails rspec 세트 하위 도메인


내 응용 프로그램을 테스트하기 위해 rSpec을 사용하고 있습니다. 내 응용 프로그램 컨트롤러에는 다음과 같은 방법이 있습니다.

def set_current_account
  @current_account ||= Account.find_by_subdomain(request.subdomains.first)
end

내 사양에서 request.subdomain을 설정할 수 있습니까? 아마도 이전 블록에 있습니까? 저는 rSpec을 처음 사용하므로 이에 대한 조언이 있으면 감사하겠습니다.

Eef


이 문제를 분류하는 방법을 알아 냈습니다.

내 사양의 이전 블록에서 간단히 추가했습니다.

before(:each) do
  @request.host = "#{mock_subdomain}.example.com"
end

이것은 request.subdomains.first를 mock_subdomain의 값으로 설정합니다.

누군가 인터넷의 다른 곳에서는 잘 설명되지 않았기 때문에 유용하다고 생각하기를 바랍니다.


나는 이것이 비교적 오래된 질문이라는 것을 알고 있지만 이것이 어떤 종류의 테스트를 실행하고 있는지에 달려 있음을 발견했습니다. 또한 Rails 4와 RSpec 3.2를 실행하고 있으므로이 질문을받은 후 몇 가지 사항이 변경되었다고 확신합니다.

사양 요청

before { host! "#{mock_subdomain}.example.com" }

Capybara의 기능 사양

before { Capybara.default_host = "http://#{mock_subdomain}.example.com" }
after  { Capybara.default_host = "http://www.example.com" }

나는 일반적으로 spec/support다음과 같은 모듈을 만듭니다 .

# spec/support/feature_subdomain_helpers.rb
module FeatureSubdomainHelpers
  # Sets Capybara to use a given subdomain.
  def within_subdomain(subdomain)
    before { Capybara.default_host = "http://#{subdomain}.example.com" }
    after  { Capybara.default_host = "http://www.example.com" }
    yield
  end
end

# spec/support/request_subdomain_helpers.rb
module RequestSubdomainHelpers
  # Sets host to use a given subdomain.
  def within_subdomain(subdomain)
    before { host! "#{subdomain}.example.com" }
    after  { host! "www.example.com" }
    yield
  end
end

포함 spec/rails_helper.rb:

RSpec.configure do |config|
  # ...

  # Extensions
  config.extend FeatureSubdomainHelpers, type: :feature
  config.extend RequestSubdomainHelpers, type: :request
end

그런 다음 다음과 같이 사양 내에서 호출 할 수 있습니다.

feature 'Admin signs in' do
  given!(:admin) { FactoryGirl.create(:user, :admin) }

  within_subdomain :admin do
    scenario 'with valid credentials' do
      # ...
    end

    scenario 'with invalid password' do
      # ...
    end
  end
end

Rails 3에서 호스트를 수동으로 설정하려고 시도한 모든 것이 작동하지 않았지만 코드를 보면 .NET과 같은 요청 도우미에게 전달하는 경로를 얼마나 잘 파싱했는지 알 수 get있습니다. 컨트롤러가 하위 도메인에 언급 된 사용자를 가져 와서 다음과 같이 저장하면 충분합니다.@king_of_the_castle

it "fetches the user of the subomain" do
  get "http://#{mock_subdomain}.example.com/rest_of_the_path"
  assigns[:king_of_the_castle].should eql(User.find_by_name mock_subdomain)
end

  • Rspec-3.6.0
  • 카피 바라-2.15.1

Chris Peters의 답변은 요청 사양에 적합했지만 기능 사양의 경우 다음과 같이 변경해야했습니다.

rails_helper :

Capybara.app_host = 'http://lvh.me'
Capybara.always_include_port = true

feature_subdomain_helpers :

module FeatureSubdomainHelpers
    def within_subdomain(subdomain)
        before { Capybara.app_host = "http://#{subdomain}.lvh.me" }
        after  { Capybara.app_host = "http://lvh.me" }
        yield
    end
end

참조 URL : https://stackoverflow.com/questions/2556627/rails-rspec-set-subdomain

반응형