如何在不同文件中使用 Rspec shared_examples?

问题描述 投票:0回答:1

我想在不同的规范文件中重用这个

shared_examples
块。我想将其提取到一个单独的文件中,并传入对象,因此它并不总是用户的。我尝试的两种方法都失败了,这可能吗?

describe User  do
  before  { @user = build_stubbed(:user) }
  subject { @user }

  shared_examples 'a required value' do |key| # trivial example, I know
    it "can't be nil" do
      @user.send("#{key}=", nil)
      @user.should_not be_valid
    end
  end

  describe 'name'
    it_behaves_like 'a required value', :name
  end
end
ruby testing rspec
1个回答
7
投票

只是

require
另一个文件。
shared_examples
在顶层工作,因此一旦定义它们就始终可用;所以要小心命名冲突。

很多 RSpec 用户会将共享示例放在

spec/support/shared_examples/FILENAME.rb
中。然后在
spec/spec_helper.rb
中有:

Dir["./spec/support/**/*.rb"].sort.each {|f| require f}

或者在 Rails 项目上

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

这列在共享示例文档的“约定”部分中。

© www.soinside.com 2019 - 2024. All rights reserved.