RSpec &Rails:存根@virtual_path 用于翻译助手以测试应用程序助手 [英] RSpec & Rails: Stub @virtual_path for translation helper to test an application helper

查看:27
本文介绍了RSpec &Rails:存根@virtual_path 用于翻译助手以测试应用程序助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ApplicationHelper 中有一个助手 page_title_default:

I have a helper page_title_default in ApplicationHelper:

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

现在我想这样测试:

describe '#page_title' do
  subject { page_title }

  it { ... }
end

结束

这会导致以下错误:

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

根据这篇文章应该可以像这样存根 @virtual_path 变量:

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")

但这似乎没有帮助:虽然我能够存根,然后在测试中直接调用类似 helper.t '.something' 的东西,但它不适用于在 page_title_default 方法中使用的翻译助手(仍然将 @virtual_path 设置为 nil).所以它似乎不是翻译助手的同一个实例.但是我怎样才能找到自己的 page_title_default 方法呢?

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?

推荐答案

怎么样:

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

我们对此处返回的已翻译"字符串进行存根处理,以将 helper 的规范与真实"翻译分离,这对于 PageHelper 本身 - 每次更改.title"的翻译时测试都会失败.

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".

另一方面 - 如果您更改使用的密钥,例如.从.title"到.default_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.

希望有帮助!

这篇关于RSpec &Rails:存根@virtual_path 用于翻译助手以测试应用程序助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆