简体   繁体   English

确定要在RSpec中存根的类或实例

[英]Determining what class or instance to stub in RSpec

Let's say I have a helper method in my Rails initializer, which makes it essentially available everywhere in my app 假设我在Rails初始化程序中有一个辅助方法,该方法使该方法实际上在我的应用程序中的任何地方都可用

# config/initializers/foo.rb
def foo
  "FOO"
end

And then I use it while rendering a view 然后我在渲染视图时使用它

<div class="container">
  <%= t("some.translation", link: foo) %>
</div>

I want to stub that value in my feature specs (not view specs). 我想在功能规格 (而不是视图规格)中存根该值。 That means I want have one of the following - 这意味着我想要以下内容之一-

expect_any_instance_of(<some class instance>).to receive(:foo) { "BAR" }
expect(<some class>).to receive(:foo) { "BAR" }
  1. What is the <some_class> or instance that I need to fill in here? 我需要在这里填写什么<some_class>或实例? What class acts as the recipient for view methods? 什么类充当视图方法的接收者?

  2. In general, how do I find the recipient of any arbitrary method so I can stub it out in a similar fashion? 通常,如何找到任意方法的接收者,以便以类似的方式将其存根?

From the docs 来自文档

Feature specs are high-level tests meant to exercise slices of functionality through an application. 功能规格是高级测试,旨在通过应用程序行使功能性。 They should drive the application only via its external interface, usually web pages. 他们应该仅通过外部接口(通常是网页)来驱动应用程序。

which implies you really shouldn't be stubbing anything in a feature spec. 这意味着您真的不应该在功能说明中添加任何内容。

It sounds like your foo method is a view helper method specifically. 听起来您的foo方法是专门用于视图的帮助器方法。 If that is the case, then that method does not belong in an initializer. 如果是这种情况,则该方法不属于初始化程序。 Initializers should hold code that should be run as the application starts up (or code for monkey-patching gems). 初始化程序应保存应在应用程序启动时运行的代码(或用于猴子修补gem的代码)。

Methods that help with the view layer should be listed in app/helpers/application_helper (or a new custom file in that same directory). 应在app/helpers/application_helper (或同一目录中的新自定义文件)中列出有助于视图层的方法。 That's what helper files are for - view level methods. 这就是帮助文件的用途-视图级方法。

At that point, what you're trying to do is stub out a helper method. 那时,您想做的是将辅助方法存根。 This SO Question as well as this one should help you with that. 这样的问题以及这个 问题都应该帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM