LoginSignup
5
5

More than 5 years have passed since last update.

サブドメインを指定して、featureスペックを実行する

Posted at

あまり必要になることはないと思いますが、特定のサブドメインで動作するようなコードを書いている場合、feature スペックの対象サブドメインを指定したくなることがあります。
備忘録がてらまとめます。

やり方は割と簡単。

specs/features/users_spec.rb
require "rails_helper"

feature "Users", type: :feature, js: true do
  background(:all) do
    Capybara.default_host = 'http://subdomain.lvh.me'
    Capybara.app_host = 'http://subdomain.lvh.me'
    Capybara.always_include_port = true
  end

  after(:all) do
    Capybara.default_host = 'http://www.example.com'
    Capybara.app_host = nil
    Capybara.always_include_port = false
  end
   :

これは subdomain. というサブドメインに対して feature スペックを実行したい場合。
background というのは before のエイリアスです。
after でデフォルトの状態に戻しているのは、こうしないと他のテストが落ちる場合があるからです。

lvh.me とはなんぞや?という感じですが、平たく言えば localhost と同じで、 127.0.0.1 に割り当てられています。

$ nslookup lvh.me
Server:     192.168.100.254
Address:    192.168.100.254#53

Non-authoritative answer:
Name:   lvh.me
Address: 127.0.0.1

localhost のままだとサブドメインつけられないし、hosts を変更するわけにもいかないし、となるこんな状況にまさに打ってつけですね。

プロジェクトによっては除外URLの指定が必要です。

specs/rails_helper.rb
RSpec.configure do |config|
  Capybara::Webkit.configure do |c|
    c.block_unknown_urls
    c.allow_url("admin.lvh.me")
  end
  Capybara.default_selector  = :css
      :

こちらのサイトを参考にしました。
Acceptance Tests with Subdomains

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5