不建议访问跨上下文定义的shared_examples

时间:2013-09-16 09:17:01

标签: ruby-on-rails rspec

我在我的rails应用程序上使用rspec,我更新了我的宝石。现在,当我运行测试时,我有以下消息:

Accessing shared_examples defined across contexts is deprecated.
Please declare shared_examples within a shared context, or at the top level.
This message was generated at: /home/flo/RoR/letroquet/spec/requests/user_show_page_spec.rb:50:in `block (3 levels) in <top (required)>'

以下是 user_show_page_spec.rb

describe "show user page" do

  subject { page }

  let(:user) { FactoryGirl.create(:user) }
  let(:current_page) { user_path(user) }

  describe "aside info" do

    describe "when not signed-in" do
      before { visit current_page }

      it { should have_selector('h1', text: user.name) }

      it_should_behave_like "another user products count" # This is the 50th line
    end
  end
end

这里是 spec / support / users / info.rb

require 'spec_helper'

describe "products count" do
  subject { page }

  shared_examples_for "another user products count" do
    before { visit current_page }

    it { should have_selector('b', text: t('product.owned.count', count: user.transactions.current.ownership.count)) }
    it { should have_selector('li', text: t('product.givable.count', count: user.products.owned.givable.count)) }
    it { should have_selector('li', text: t('product.sharable.count', count: user.products.owned.sharable.count)) }
    it { should have_selector('li', text: t('product.borrowed.count', count: user.products.borrowed.count)) }

    it { should have_selector('li', text: t('product.given.count', count: user.products.given.count)) }
    it { should have_selector('li', text: t('product.returned.count', count: user.products.returned.count)) }

  end
end

你能告诉我如何更改我的测试文件吗?

1 个答案:

答案 0 :(得分:1)

http://myronmars.to/n/dev-blog/2013/07/rspec-2-14-is-releasedhttps://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

中给出的示例讨论了这一主题

根据该文档,您需要通过直接包含或使用'require'将示例放在其使用范围内。在任何情况下,请注意shared_examples_for调用必须在范围内,不能像describe中的代码一样隐藏在info.rb内。

因此,假设您的spec_helper.rb文件已自动包含spec/support中的文件,您可以将info.rb文件更改为:

shared_examples_for "another user products count" do
  subject { page }
  before { visit current_page }

  it { should have_selector('b', text: t('product.owned.count', count: user.transactions.current.ownership.count)) }
  it { should have_selector('li', text: t('product.givable.count', count: user.products.owned.givable.count)) }
  it { should have_selector('li', text: t('product.sharable.count', count: user.products.owned.sharable.count)) }
  it { should have_selector('li', text: t('product.borrowed.count', count: user.products.borrowed.count)) }

  it { should have_selector('li', text: t('product.given.count', count: user.products.given.count)) }
  it { should have_selector('li', text: t('product.returned.count', count: user.products.returned.count)) }

end

它应该有效。请注意,subject调用已在共享示例块中移动。