2010-10-27 36 views
19

Tôi đã xem phương thức trợ giúp tạo url bằng cách xem request.domain và request.port_string.Làm thế nào để thử đối tượng yêu cầu cho các thử nghiệm trợ giúp rspec?

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

Tôi muốn thử nghiệm phương pháp này bằng rspec.

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

Nhưng khi tôi chạy này với rspec, tôi có được điều này:

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

bất cứ ai có thể vui lòng giúp tôi tìm ra những gì tôi nên làm gì để khắc phục điều này? Làm cách nào tôi có thể thử đối tượng 'yêu cầu' cho ví dụ này?

Có cách nào tốt hơn để tạo url mà tên miền phụ được sử dụng không?

Xin cảm ơn trước.

Trả lời

21

Bạn cần phải thêm vào trước các phương pháp helper với 'helper':

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

Ngoài ra để kiểm tra hành vi cho các tùy chọn yêu cầu khác nhau, bạn có thể truy cập vào các đối tượng yêu cầu Xuyên điều khiển:

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 
+2

Đó là lỗi: Ngoại lệ gặp phải: # shailesh

7

tôi có vấn đề tương tự, tôi thấy giải pháp này hoạt động:

before(:each) do 
    helper.request.host = "yourhostandorport" 
end 
+0

Đối với tôi trong bộ điều khiển nó làm việc với 'điều khiển. request.host = "http://test_my.com/" ' – AnkitG

9

Đây không phải là câu trả lời hoàn chỉnh cho câu hỏi của bạn, nhưng đối với hồ sơ, bạn có thể thử một yêu cầu bằng cách sử dụng ActionController::TestRequest.new(). Một cái gì đó như:

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 
+0

Bạn có thể xây dựng? –

Các vấn đề liên quan