Create custom rspec variable like response for controller specs - ruby-on-rails

I want to create a custom variable similar to response object that should only be available in controller specs. I noticed that rspec supports filters which are before/after hooks which means I can create instance variables with them to be used later. But response object feels and works more like a let variable that is lazily evaluated. Also, controller specs support assign method that can accept arguments.
Does rspec support any way to create similar methods to be used with a specific type of spec?
Note: I don't need to support anything below rspec 3.0.

You can simply do this by creating a module with your function and then including that in your RSpec configure block. You can control the types of specs where this should be available as a second parameter when you include the module:
module ControllerSpecHelpers
def something
'fubar2000'
end
end
RSpec.configure do |config|
config.include ControllerSpecHelpers, type: :controller
end
RSpec.describe BlahController, type: :controller do
it 'should be possible to use the `something` helper in a controller spec' do
expect(something).to eq('fubar2000')
end
end

Related

How do I test helpers in Rails 4?

With this ApplicationHelper:
class ApplicationHelper
def my_method
link_to 'foo', 'bar'
end
end
and this application_helper_spec:
require 'rails_helper'
describe ApplicationHelper do
describe 'links' do
it 'should call a helper method' do
expect(helper.my_method).to eq("<a href='bar'>foo</a>")
end
end
end
I'm having trouble getting things to work as as I expected from the latest documentation I can find on Rails helper specs. (The docs are for Ruby 3 and I'm using 4.) There doesn't appear to be a helper object:
undefined local variable or method `helper' for #<RSpec::ExampleGroups::ApplicationHelper::Links:0x007fda1895c2f8>
If instead I do this:
require 'rails_helper'
include ApplicationHelper
describe ApplicationHelper do
describe 'links' do
it 'should call a helper method' do
expect(my_method).to eq("<a href='bar'>foo</a>")
end
end
end
now my_method is called correctly but link_to is not defined:
undefined method `link_to' for #<RSpec::ExampleGroups::ApplicationHelper::Links:0x007fda1c4c3e90>
(This latter case is the same as if I define config.include ApplicationHelper in rails_helper.)
Obviously the spec environment does not include all the standard Rails helpers. What am I doing wrong here?
You need to either enable the infer_spec_type_from_file_location! option, or explicitly set the test type, e.g.:
describe ApplicationHelper, type: :helper do
...
end
I think that Andy Waite's answer regarding defining type: :helper on your spec is correct in that it will solve your undefined local variable or method 'helper' issues.
However, as for the overarching question of "How do I test helpers in Rails 4?", and specifically your method that seems to just make a call to ActionView::Helpers::UrlHelper#link_to, assuming that you don't want to cover this in a feature spec and want to test it in isolation, consider that if you want to test that "calling #my_method returns a string containing HTML for a foo bar link", the link_to tests for UrlHelper itself would confirm that calling link_to 'foo', 'bar' will return "<a href='bar'>foo</a>".
So, I'd suggest moving your specs up one level higher, saying that you want to test that "calling #my_method returns me a link for foo bar (in whatever way Rails hands me back links)":
require 'rails_helper'
RSpec.describe ApplicationHelper, type: :helper do
describe '#my_method' do
it 'returns a foo bar link' do
expect(helper).to receive(:link_to).with('foo', 'bar')
helper.my_method
end
end
end
Personally though, I don't think this method has enough logic in it to warrant testing in isolation in a helper spec, and you'd be better off covering it in a feature spec where I assume you'd be testing for the display of the link, or clicking it to see what happens etc.

Include the I18n helpers in Rspec Tests for Services

I'm making use of Services in my app, which is not one of the "standard" app components.
Let's say I have a spec test as follows
require "rails_helper"
# spec/services/create_user.rb
RSpec.describe CreateUser, type: :service do
it "returns the error message" do
error_message = Foo.new.errors
expect(error_message).to eq(t("foo.errors.message"))
end
end
Just testing that the string returned matches a specific translation string.
However this throws an error because the helper t() isn't available.
I could refer it to explicitly as I18n.t(), but for my own curiosity, how do I include the correct module to have the luxury of calling the shorthand form?
Thanks!
You should be able to add it to the RSpec configuration using;
RSpec.configure do |config|
config.include AbstractController::Translation
end
Which means you can then just use t() instead of I18n.t()

Rspec Controller testing in Rails a controller that inherits from AbstractController::Base

I am writing controller tests for an application that I did not build, so it's definitely been a learning process. This is my first time encountering a controller that inherits directly from AbstractController::Base. It does not behave, obviously, the same as other controllers.
Its format is roughly:
class SchwadGenericController < AbstractController::Base
def schwad_method var_one, var_two = nil, var_three = nil
if var_two.blank?
var_one.generic_method
end
render template: "schwad_templates/generic_template", layout: false
end
end
I tried normal testing, this is where I am currently at to get ANYTHING to happen.
require 'rails_helper'
describe SchwadGenericController do
# before(:each) do
# SchwadGenericController.skip_authorize_resource
# end
# login_user
let!(:variable){ create(:my_factory_variable) }
describe 'controller methods' do
it 'should hit this method' do
binding.pry
SchwadGenericController.schwad_method(variable)
# expect(response).to_render template: "schwad_templates/generic_template"
end
end
end
And here is roughly where my failures are landing.
Failures:
1) SchwadGenericController controller methods should hit this method
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `request=' for # <SchwadGenericController:0x007f8022db0a20>
I read up on abstract controllers and their role in rails here: https://www.mobomo.com/2012/06/and-you-thought-render-farms-were-just-for-pixar/
I read up on the docs here: http://api.rubyonrails.org/classes/AbstractController/Base.html
I would really appreciate another set of eyes on this and guidance as to how you guys have tested controllers and their methods, with controllers that are inheriting from AbstractController::Base.... What am I missing?
-Schwad
After some testing, I don't think this is possible. Controller specs are just wrappers for Rails functional tests which test classes inheriting from ActionController::Base. For controller tests to even run, the controller must support the request and response objects, which is not the case of AbstractController::Base (these are defined in ActionController::Base). That is why you get the particular error when you run the test. For the same reason, you will not be able to use the controller spec helpers (expects) such as to_render because, again, they are defined only for controller specs and your controller class is not a "controller" in the "controller specs" sense.
The only option you seem to have for testing is to test the controller just as any other plain ruby class. You'd need to move your test out of the spec/controllers directory to some other, e.g. spec/abstract_controllers and then you'd have to give up all controller spec helpers and test just calling the instance methods, e.g.:
describe 'controller methods' do
it 'should hit this method' do
c = SchwadGenericController.new
expect(c).to receive(:render).with(template: "schwad_templates/generic_template", layout: false)
c.schwad_method(variable)
end
end
Extending directly from AbstractController::Base seems the likely source of the error to me. Unless you're doing something very nonconventional there should be no reason to do this.
Are you sure you don't intend to inherit from ActionController::Base? There's a whole bunch of modules in ActionController required for rendering which is probably explains the error on a missing method in your tests.
If switching to ActionController::Base doesn't work. Try running app.get "/path/to/action" from the rails console. Do you get the same error?

RSpec page variable

How is it that rspec feature tests implicitly know to use methods such as find, within, and fill_in from the page object?
I've written a helper class for some of my rspec tests and wanted to use those methods, and realized that I needed to pass the page object into the method, and then use page.find and the like.
RSpec achieves this by including Capybara::DSL in those cases where it wants those methods available. The module is pretty elegant, if you want to take a look at https://github.com/jnicklas/capybara/blob/f83edc2a515a3a4fd80eef090734d14de76580d3/lib/capybara/dsl.rb
suppose you want to include the following module:
module MailerMacros
def last_email
ActionMailer::Base.deliveries.last
end
def reset_email
ActionMailer::Base.deliveries = []
end
end
to include them, just call config.include(MailerMacros), like this:
RSpec.configure do |config|
config.include(MailerMacros)
end
now, you should be able to call reset_email() & last_email instead of MailerMacros::reset_email().

Adding Controller Macros in Rspec

Im trying to define some controller macros for Rspec. Im using rails 3 and have my macros defined in spec/support/macros/controller_macros.rb, that file looks like this:
module ControllerMacros
def self.login_admin
#code
end
end
in my spec helper I have:
config.include(ControllerMacros, :type => :controller)
So in my controller spec i just call login_admin in my admin tests but when ever i use the method i get
undefined local variable or method `login_admin' for #<Class:0xb6de4854> (NameError)
At first I assumed that controller_macros.rb wasn't being included but when I added a "puts" to the file but that showed the file was at least being executed.
I can't see anything wrong with my setup and copying the login_admin method into the describe block works fine so im not sure whats wrong with it.
Maybe I am late to that, but for new comers.
Here is a good examples of using macros:
http://osmose.6spot.com.br/2011/01/rails-resource-routing-spec-w-rspec/
when you include a module it's methods are visible inside examples.
But when you extend the module, it's methods are only visible outside examples.
It gives you ways to compose your macros for each situation.
Try
ControllerMacros.login_admin
or remove self from the method definition.
One line answer: Remove self from the method definition
Why? The methods of included modules are available in RSpec examples
The login_admin method defined in ControllerMacros will be available in your RSpec example as login_admin
To Be Specific:
Rewrite spec/support/macros/controller_macros.rb as
module ControllerMacros
def login_admin
#code
end
end
Then tell Rspec to include the Macros
config.include(ControllerMacros, :type => :controller)

Resources