25

request.domain と request.port_string を見て URL を生成するビュー ヘルパー メソッドがあります。

   module ApplicationHelper  
       def root_with_subdomain(subdomain)  
           subdomain += "." unless subdomain.empty?    
           [subdomain, request.domain, request.port_string].join  
       end  
   end  

このメソッドを rspec を使用してテストしたいと思います。

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    root_with_subdomain("test").should = "test.xxxx:xxxx"
  end
end

しかし、これを rspec で実行すると、次のようになります。

 Failure/Error: root_with_subdomain("test").should = "test.xxxx:xxxx"
 `undefined local variable or method `request' for #<RSpec::Core::ExampleGroup::Nested_3:0x98b668c>`

誰でもこれを修正するために何をすべきかを理解するのを手伝ってもらえますか? この例の「リクエスト」オブジェクトをモックするにはどうすればよいですか?

サブドメインが使用されている URL を生成するより良い方法はありますか?

前もって感謝します。

4

4 に答える 4

23

ヘルパー メソッドの先頭に「helper」を追加する必要があります。

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    helper.root_with_subdomain("test").should = "test.xxxx:xxxx"
  end
end

さらに、さまざまなリクエスト オプションの動作をテストするために、コントローラーを介してリクエスト オブジェクトにアクセスできます。

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    controller.request.host = 'www.domain.com'
    helper.root_with_subdomain("test").should = "test.xxxx:xxxx"
  end
end
于 2010-11-08T14:27:47.630 に答える
12

これはあなたの質問に対する完全な回答ではありませんが、記録のために、 を使用してリクエストをモックできますActionController::TestRequest.new()。何かのようなもの:

describe ApplicationHelper do
  it "should prepend subdomain to host" do
    test_domain = 'xxxx:xxxx'
    controller.request = ActionController::TestRequest.new(:host => test_domain)
    helper.root_with_subdomain("test").should = "test.#{test_domain}"
  end
end
于 2012-05-04T11:24:57.367 に答える
8

私は同様の問題を抱えていました、私はこの解決策が機能することを発見しました:

before(:each) do
  helper.request.host = "yourhostandorport"
end
于 2011-06-08T02:13:41.823 に答える