0

Let's say I have a helper method in my Rails initializer, which makes it essentially available everywhere in my app

# 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? 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?

user2490003
  • 10,706
  • 17
  • 79
  • 155

2 Answers2

1

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.

zetetic
  • 47,184
  • 10
  • 111
  • 119
  • Ok, what about the 2nd part of the question: "In general, how do I find the recipient of any arbitrary method so I can stub it out in a similar fashion?". Regardless of feature specs or non-feature specs, and regardless of what's considered correct, how does one even determine what class/object is going to be receiving a message? – user2490003 Mar 08 '16 at 18:01
0

It sounds like your foo method is a view helper method specifically. 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).

Methods that help with the view layer should be listed in app/helpers/application_helper (or a new custom file in that same directory). 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.

Community
  • 1
  • 1
Jack Collins
  • 1,145
  • 10
  • 21
  • Thanks. The implementation of the `:foo` method is somewhat outside the scope of this question - lets say it's something specific to my application that I choose to use in various places, even outside of views. The heart and spirit of the question is whether stubbing that out (assuming it is an initializer method) is possible – user2490003 Mar 01 '16 at 19:44