3

I have a helper page_title_default in ApplicationHelper:

def page_title_default(options = {})
  t '.title', options
end

Now I want to test it like this:

describe '#page_title' do
  subject { page_title }

  it { ... }
end

end

This results in the following error:

Cannot use t(".title") shortcut because path is not available

According to this post it should be possible to stub the @virtual_path variable like this:

helper.instance_variable_set(:@virtual_path, "admin.path.form")

But this doesn't seem to help: While I am able to stub it and then to call something like helper.t '.something' directly in the test, it doesn't work for the translation helper which is used in the page_title_default method (which still has @virtual_path set to nil). So it seems it's not the same instance of translation helper. But how can I find the page_title_default method one's?

1 Answer 1

6

How about something like:

RSpec.describe PageHelper, :type => :helper do
  describe "#page_title_default" do
    before do
      allow(helper).to receive(:t).with(".title", {}) { "Hello!" }
    end

    subject { helper.page_title_default }

    it { is_expected.to eq "Hello!" }
  end
end

We're stubbing the "translated" string returned here to decouple the spec of helper from "real" translations, which may appear to be fragile for the test of PageHelper itself - the tests would fail every time you change the translations of ".title".

On the other hand - if you change the key used, eg. from ".title" to ".default_title" it should fail, because it is change of behaviour.

I think the proper text displayed should be tested on different level of test (integration tests, to be specific). Please, check the following answer.

Hope that helps!

2
  • This works, nice! But why do I need to call explicit subject { helper.xxx }? When only having subject { xxx }, it doesn't work. What's the implicit receiver in the 2nd code? Why isn't it the same as the explicit one? Apr 2, 2015 at 11:55
  • Hey! This is interesting question! This is because the method would be called in context of your test (internally, they are classes), so call like this would end up with error similar to undefined local variable or method 'page_title_default' - which is true, because this method is not implemented in your test. You could use it this way, if you defined that method within describe block - def page_title_default; helper.page_title_default end. Please check my other answer. Apr 2, 2015 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.