Reputation: 43123
I'm a little unsure as to how to write a test for a helper method which has output that is based on the given controller and action that are requested.
Given the following helper method in my application helper...
module ApplicationHelper
def body_id
[ controller.controller_name, controller.action_name ].join("_")
end
end
... how would you write an application_helper_spec
that tests this method?
Upvotes: 0
Views: 1158
Reputation: 987
rspec-rails has some built sugar for testing helpers as @marnen-laibow-koser mentioned. But I sometimes like to write very lightweight tests for my helpers that don't have to load in my whole rails environment. This way the tests can run in less than a second as opposed to the multiple seconds it takes to load the rails environment.
Here is an example:
require 'spec_helper_lite'
require_relative '../../app/helpers/application_helper'
describe ApplicationHelper do
let(:helper) do
class Helper
include ApplicationHelper
end
Helper.new
end
it "formats an elapsed time as a number of minutes and seconds" do
helper.elapsed_as_min_sec(90).should == "1min 30sec"
end
end
And my spec_helper_lite.rb file just looks like this:
require 'rspec'
require 'rspec/autorun'
RSpec.configure do |config|
config.order = "random"
end
Upvotes: 0
Reputation: 6337
Assign or mock the controller object. That will give you something to test against. (RSpec includes a very good mocking/stubbing library.)
Upvotes: 2