After upgrading to Rails 6.1, a test helper spec on RSpec 3.11.0 seems to be broken:
# helpers/my_helper.rb
module MyHelper
def foobar
controller.controller_name.to_sym
end
end
My test looks like this
# spec/helpers/my_helper_spec.rb
describe MyHelper do
it "foo" do
expect(foobar).to eq(:test)
end
end
and throws this error
1) MyHelper foo
Failure/Error: controller.controller_name.to_sym
NoMethodError:
undefined method `to_sym' for nil:NilClass
# ./app/helpers/my_helper.rb:5:in `foobar'
Before the upgrade on Rails 6.0, controller.controller_name
was just set to "test"
, but now it's nil
.
Do I have to set a controller name now explicitly?
CodePudding user response:
I'm not 100% sure that this will fix your problem but try to add type: :helper
to your describe
statement:
describe MyHelper, type: :helper do
it "foo" do
expect(foobar).to eq(:test)
end
end
CodePudding user response:
I found out whats going on, compare these two lines:
https://github.com/rails/rails/blob/v6.0.5/actionview/lib/action_view/test_case.rb#L104
@controller = ActionView::TestCase::TestController.new
https://github.com/rails/rails/blob/v6.1.6/actionview/lib/action_view/test_case.rb#L105
controller_class = Class.new(ActionView::TestCase::TestController)
In Rails 6.1, controller_class
is an anonymous class with no name. And because controller.controller_name
uses the class' name, it returns nil
. I solved it by stubbing it like this:
allow(controller).to receive(:controller_name).and_return("test")
However, the reasoning behind this decision would be interesting. Maybe they wanted tests to be more explicit what the controller name is. This is the commit that changed that line https://github.com/rails/rails/commit/3ec8ddd0cf3851fd0abfc45fd430b0de19981547