Rails rspec set subdomain

后端 未结 4 1011
暗喜
暗喜 2020-12-01 04:07

I am using rSpec for testing my application. In my application controller I have a method like so:

def set_current_account
  @current_account ||= Account.fi         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 04:35

    I know this is a relatively old question, but I've found that this depends on what kind of test you're running. I'm also running Rails 4 and RSpec 3.2, so I'm sure some things have changed since this question was asked.

    Request Specs

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

    Feature Specs with Capybara

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

    I usually create modules in spec/support that look something like this:

    # 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
    

    Include in spec/rails_helper.rb:

    RSpec.configure do |config|
      # ...
    
      # Extensions
      config.extend FeatureSubdomainHelpers, type: :feature
      config.extend RequestSubdomainHelpers, type: :request
    end
    

    Then you can call within your spec like so:

    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
    

提交回复
热议问题