2012-08-31 11 views
5

私は現在、レールテストの長い旅の終わりにいますが、サブドメインで動作するリクエスト仕様を取得する方法については頭を悩ましています。capybara/rspecのサブドメインをテストします

開発中、私は、すべての罰金とダンディーのようなURLを持つpowを使用しています:http://teddanson.myapp.dev/account

テストでは、私はカピバラにローカルホストhttp://127.0.0.1:50568/accountを返すようにしましたが、これは明らかにサブドメイン全体のものでうまくいきません。サブドメインを必要としないアプリの公開部分はうまく動作しますが、特定のユーザーのサブドメインアカウントにアクセスする方法は私の外です。

関連するルート

は、これらのメソッドを介してアクセスされています

class Public 
    def self.matches?(request) 
    request.subdomain.blank? || request.subdomain == 'www' 
    end 
end 

class Accounts 
    def self.matches?(request) 
    request.subdomain.present? && request.subdomain != 'www' 
    end 
end 

私は狂気の丸薬を取っているように私は感じるので、誰も私を助けるために何かアドバイスや提案を持っている場合は、非常に、非常に素晴らしいことです。ご協力いただきありがとうございます!

答えて

2

、ここで説明するように、カピバラ/ RSpecの中でサブドメインをテストするためにxip.ioを使用することができます。http://www.chrisaitchison.com/2013/03/17/testing-subdomains-in-rails/

+0

詳細なとエレガントな解決策を37signalsのを使用してxip.io.ありがとうございました! @cmaitchison – BenU

+0

元の記事の著者はxip.ioを使用しています。しかし、それはそのようなテストがインターネット接続を必要とすることを意味し、それがなければ落ちるでしょう!また、テストスーツを遅くする必要があるのは、サブドメインを使用した各テストで最初にサイトに移動するためです。 – ExiRe

1

残念ながら、capybaraのテストでサブドメインを使用することはできませんが、この問題の回避策があります。私は要求からサブドメインを解決するためのヘルパークラスを持っている 、以下を参照してください

class SubdomainResolver 
    class << self 
    # Returns the current subdomain 
    def current_subdomain_from(request) 
     if Rails.env.test? and request.params[:_subdomain].present? 
     request.params[:_subdomain] 
     else 
     request.subdomain 
     end 
    end 
    end 
end 

ご覧のとおり、アプリはtestモードで実行されていて、特別な_subdomain要求のparamは、サブドメインが要求のparamから取得され設定されている場合_subdomainと呼ばれ、それ以外の場合はrequest.subdomain(通常のサブドメイン)が使用されます。

あなたもURLビルダーをオーバーライドする必要があり、この回避策を動作させるために、app/helpersに以下のモジュールを作成します。

module UrlHelper 
    def url_for(options = nil) 
    if cannot_use_subdomain? 
     if options.kind_of?(Hash) && options.has_key?(:subdomain) 
     options[:_subdomain] = options[:subdomain] 
     end 
    end 

    super(options) 
    end 

    # Simple workaround for integration tests. 
    # On test environment (host: 127.0.0.1) store current subdomain in the request param :_subdomain. 
    def default_url_options(options = {}) 
    if cannot_use_subdomain? 
     { _subdomain: current_subdomain } 
    else 
     {} 
    end 
    end 

    private 

    # Returns true when subdomains cannot be used. 
    # For example when the application is running in selenium/webkit test mode. 
    def cannot_use_subdomain? 
    (Rails.env.test? or Rails.env.development?) and request.host == '127.0.0.1' 
    end 
end 

SubdomainResolver.current_subdomain_fromconfig/routes.rb

に制約としても使用することができ、私はそれはあなたを助けることを願っています。