Ruby 如何在Rspec中只运行特定的测试?

Ruby 如何在Rspec中只运行特定的测试?,ruby,rspec,Ruby,Rspec,我认为有一种方法可以只运行带有给定标签的测试。有人知道吗?或者,您可以传递行号:rspec spec/my_spec.rb:75-行号可以指向单个spec或一个上下文/描述块,该块中运行所有spec查找文档并不容易,但您可以使用散列标记示例。例如 # spec/my_spec.rb describe SomeContext do it "won't run this" do raise "never reached" end it "will run this", :foc

我认为有一种方法可以只运行带有给定标签的测试。有人知道吗?

或者,您可以传递行号:rspec spec/my_spec.rb:75-行号可以指向单个spec或一个上下文/描述块,该块中运行所有spec

查找文档并不容易,但您可以使用散列标记示例。例如

# spec/my_spec.rb
describe SomeContext do
  it "won't run this" do
    raise "never reached"
  end

  it "will run this", :focus => true do
    1.should == 1
  end
end

$ rspec --tag focus spec/my_spec.rb
更多信息。任何人与更好的链接,请建议

更新

RSpec现在是。有关详细信息,请参见本节

从v2.6开始,通过包含配置选项treat_symbols_As_metadata_keys_with_true_value,可以更简单地表示此类标记,这允许您执行以下操作:

描述很棒的功能:很棒的做

其中:awesome被视为:awesome=>true


另请参阅,了解如何配置RSpec以自动运行“聚焦”测试。这在以下情况下尤其有效。

您可以运行包含特定字符串的所有测试:


我最常用的一个。

您还可以将多个行号与冒号连在一起:

$ rspec ./spec/models/company_spec.rb:81:82:83:103
输出:

Run options: include {:locations=>{"./spec/models/company_spec.rb"=>[81, 82, 83, 103]}}

从RSpec 2.4开始,我想您可以在它前面加上f或x,指定、描述和上下文:


确保在spec\u helper.rb中配置config.filter\u run focus:true和config.run\u all\u,此时spec\u helper.rb中的\u everything\u filtered=true。

确保在spec\u helper.rb中配置RSpec以注意焦点:

然后在规格中,添加focus:true作为参数:

it 'can do so and so', focus: true do
  # This is the only test that will run
end
您还可以通过将其更改为适合或排除带有xit的测试来关注测试,如下所示:

fit 'can do so and so' do
  # This is the only test that will run
end

此外,您还可以运行默认为focus:true的规范

spec/spec_helper.rb

RSpec.configure do |c|
  c.filter_run focus: true
  c.run_all_when_everything_filtered = true
end
然后就跑

$ rspec
并且只运行集中测试

然后,当您移除焦点:true时,所有测试都将再次运行


更多信息:

您可以作为rspec spec/models/user_spec.rb运行-e SomeContext不会运行此操作。

在较新版本的rspec中,配置support fit更容易:

见:


所以你不必去搜索,Zettec建议的直接链接是RSpec2.12。我们在套件中添加了一个规范,以确保代码永远不会与focus合并:仍然在源代码控制中@jwg2s我使用git钩子阻止提交:focus,它还可以防止“binding.pry、console.log”等不受欢迎的东西潜入代码库。@Otherus不,我只是个粉丝:我真的很喜欢他们在津津有味上做的事情,但只是启动了自己的文档功能,因此,我们可能会看到一些竞争。也许你可以给我指出一种实际描述rspec程序使用和实际行为的文档方式:因为津津有味的文档没有。spec/spec_helper.rb总是包括在内吗?或者只有在没有选择的情况下?为什么测试模块需要“spec_helber”,并且上面的代码没有通过指定文件消除运行单个测试的可能性?我找不到关于此的任何文档。如果在项目根目录的.rspec中有-require spec_helper,则始终包含.spec_helper.rb,匹配时,它是config.filter\u run\u,只需在示例中添加:focus即可。如果意外提交了“focus:true”,则尽管未运行大多数测试,您的CI仍将通过。这太棒了!
fit 'can do so and so' do
  # This is the only test that will run
end
RSpec.configure do |c|
  c.filter_run focus: true
  c.run_all_when_everything_filtered = true
end
$ rspec
# spec_helper.rb

# PREFERRED
RSpec.configure do |c|
  c.filter_run_when_matching :focus
end

# DEPRECATED
RSpec.configure do |c|
  c.filter_run focus: true
  c.run_all_when_everything_filtered = true
end