Rspec.config before(:each)除了特定的:types

mad*_*cow 13 ruby rspec ruby-on-rails

我试图让一个before(:each)块运行所有规格除外 type: :feature.

我能让它工作的唯一方法是剪切和粘贴,并为每种类型分别配置块.(:type => :model,:type => :service等)

投机/ rails_helper.rb

# To speed up tests, stub all Paperclip saving and reading to/from S3
config.before(:each, :type => :model) do
  allow_any_instance_of(Paperclip::Attachment).to receive(:save).and_return(true)
end
Run Code Online (Sandbox Code Playgroud)

有更干的方法吗?

Yul*_*ule 17

你在前面的块中传递的是' 条件哈希 '.RSpec仅将before应用于那些符合这些条件的示例或上下文.

哈希是相当灵活的,你可以type: :model像你一样做直接的事情,但你可以用任意名称查询任何类型的元数据.

过滤运行排除为例

  :foo => 'bar'
  :foo => /^ba/
  :foo => lambda {|v| v == 'bar'}
  :foo => lambda {|v,m| m[:foo] == 'bar'}
Run Code Online (Sandbox Code Playgroud)

:foo可以是任何东西,例如,类型.但它给你一定的灵活性,特别是lambda语法能够在你想要运行你的规范的情况下非常具体.

在你的情况下,你可以做这样的事情:

config.before(:each, :type => lambda {|v| v != :feature}) do
  allow_any_instance_of(Paperclip::Attachment).to receive(:save).and_return(true)
end
Run Code Online (Sandbox Code Playgroud)


Joh*_*son 6

您可以unless通过around挂钩来判断示例元数据。

RSpec.configure do |config|
  config.around(:each) do |example|
    example.run unless example.metadata[:type].eql? :feature
  end
end
Run Code Online (Sandbox Code Playgroud)