How can I stub or mock the request.subdomains method in Rails?
-
05-07-2019 - |
Question
I am trying to write some functional tests in my rails app, and in the application_controller.rb I have this:
before_filter :current_account
def current_account
@current_account ||= Account.find_by_subdomain!(request.subdomians.first)
end
When running tests, request.subdomains
doesn't contain the valid subdomains I'm looking for and makes it impossible to run any functional tests.
Is it possible to stub the current_account
method or mock the request.subdomains
object?
Solution
In your functional test you should be able to do (using mocha):
@request.expects(:subdomains).returns(['www'])
OTHER TIPS
To me (and with Rails 2.3.4), the correct statement is
@controller.request.expects(:subdomains).returns(['www'])
since I cannot access to @request directly.
@controller.instance_variable_set(:@request, OpenStruct.new({:subdomains => 'www'}))
you can access anything in ruby :)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow