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()
Related
I don't think the type part is necessary, what does it actually do?
RSpec.describe Auction, :type => :model do
The type metadata is necessary to include the correct rspec-rails support functions. There can be different spec types, inclucing controller, view, helper, mailer etc. Look more from here. Model specs are more specifically described here.
Note: RSpec versions before 3.0.0 automatically added metadata to specs based on their location on the filesystem. In RSpec3 this behaviour must be defined separately in configuration:
# spec/rails_helper.rb
RSpec.configure do |config|
config.infer_spec_type_from_file_location!
end
Therefore - if you are using RSpec 3, then without the upper configuration you cannot ignore the type declaration when creating specs.
There is also possibility to define your own custom metadata type like this:
# set `:type` for serializers directory
RSpec.configure do |config|
config.define_derived_metadata(:file_path => Regexp.new('/spec/serializers/')) do |metadata|
metadata[:type] = :serializer
end
end
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.
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
I'm writing some Rspec tests with capybara , and as part of that I need some methods of model.
I have created my model as:
class MyModel < ActiveRecord::Base
def method_name
#some stuff..
end
end
Now, I want to use MyModel in my Rspec test cases.
I tried to includeconfig.include Models in spec_helper.rb but it throws error
Uninitialized constant Models
And when I tried to include
include MyModel.new.method_name()
it throws error `include': wrong argument type nil (expected Module) (TypeError)
Without including any model class it runs test cases, but then my test cases are useless.
Here is my Rspec test case
require 'spec_helper'
describe "State Agency Page" do
let(:state_data) { FactoryGirl.build(:state_data) }
require 'mymodel.rb'
before {visit state_modifier_path}
it "should have breadcrumb", :js=>true do
page.should have_css('.breadcrumb')
end
end
Please provide any solution.
Thanks in advance.
I don't know what you mean by "your test cases are useless", but you seem to misunderstand the role of Ruby's include method.
With Rails, or the use of the rspec-rails gem with RSpec, your classes will be autoloaded when you reference the corresponding class constant (e.g. MyModel). So there generally is no need to do manual "loading" of individual models. Just make sure you have require 'spec_helper' at the beginning of your specs.
As for the errors you were getting with your attempts to use include, I suggest you find and read a Ruby reference to understand the semantics of the include method and why each attempt of yours failed in the way it did.
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().