如何在 Rails 中存根或模拟 request.subdomains 方法?

发布于 2024-07-25 14:15:18 字数 368 浏览 5 评论 0原文

我正在尝试在我的 Rails 应用程序中编写一些功能测试,并且在 application_controller.rb 中我有这样的:

before_filter :current_account
def current_account
  @current_account ||= Account.find_by_subdomain!(request.subdomians.first)
end

运行测试时, request.subdomains 不包含我正在寻找的有效子域并且使得无法运行任何功能测试。

是否可以存根 current_account 方法或模拟 request.subdomains 对象?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

执妄 2024-08-01 14:15:19

在您的功能测试中,您应该能够执行以下操作(使用摩卡):

@request.expects(:subdomains).returns(['www'])

In your functional test you should be able to do (using mocha):

@request.expects(:subdomains).returns(['www'])
兔姬 2024-08-01 14:15:19

对我(以及Rails 2.3.4)来说,正确的说法是

@controller.request.expects(:subdomains).returns(['www'])

因为我无法直接访问@request。

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.

执妄 2024-08-01 14:15:19
@controller.instance_variable_set(:@request, OpenStruct.new({:subdomains => 'www'}))

你可以访问 ruby​​ 中的任何内容:)

@controller.instance_variable_set(:@request, OpenStruct.new({:subdomains => 'www'}))

you can access anything in ruby :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文