Helper methods - RSpec Core
You can define methods in any example group using Ruby's def
keyword or define_method
method. These helper methods are exposed to examples in the group in which they are defined and groups nested within that group, but not parent or sibling groups.
Related cards:
How to define helper methods in magic DSL code
We use the lambda-technique to DRY up our Rails routes machinist blueprints, and, of course, RSpec examples.
How to use helper methods inside a model
Simple
If you want to use a helper_method my_helper_method
inside a model, you can write
ApplicationController.helpers.my_helper_method
More flexible
If you need a bit more flexibility, for example if you also n...
How to use helper methods in a controller
Rails 3+
view_context.helper_method('args')
Rails 2
ApplicationController.helpers.helper_method('args')
Also see [How to use helper methods inside a model](https://makandracards.com/makandra/1307-how-to-use-hel...
Stub methods on any instance of a class in Rspec 1 and Rspec 2
RSpec 1 (Rails 2)
With the most recent spec_candy.rb
helpers you can say:
User.stub_any_instance(:foo => :bar)
user = User.new
u...
Stubbed class methods in RSpec 1 remain stubbed in other examples
I encountered a bug in RSpec 1.x where stubbed class methods ("static methods") would not be unstubbed before the next example, causing it to fail. This behavior can come and go as you edit your specs, since this can change the order in which RSpe...
Rails: Accessing helper methods from a controller
In Rails 5+ you can access a helper from a controller using the helpers
method:
# Inside a controller action
helpers.link_to 'Foo', foo_path
In older Rails versions you can use view_context
instead:
# Inside a controller...
How to fix: WrongScopeError when using rspec_rails with Rails 6.1
tl;dr: Upgrade the gem to at least 4.0.1
When you use rspec_rails
in a version < 4 with Rails 6.1 you may encounter an error like this:
Failure/Error:
raise WrongScopeError,
"`#{name}` is not available from within an example (e.g. an ...
RSpec: How to turn off partial double verification temporarily
While verifying doubles in RSpec is a good default, it is limited in the amount of methods it actually is able to verify.
The background is that RSpec can't verify dynamica...
Spec "content_for" calls in helpers
This only applies to RSpec below version 1.3.2. The issue has been fixed in RSpec 1.3.2, and most likely RSpec 2 and later versions.
When you have a helper that calls content_for
and want to check its behavior you should probably...
Migrating to RSpec 2 from RSpec 1
You will need to upgrade to RSpec >= 2 and rspec-rails >= 2 for Rails 3. Here are some hints to get started:
- In RSpec 2 the executable is
rspec
, notspec
. - RSpec and rspec-rails have been completely refactored internally. All RSpec classes...