3

我的测试如下所示:

<<< spec/models/user_shared.rb

shared_examples_for "a user" do
end

<<< spec/models/worker_spec.rb

require 'spec_helper'
require 'models/user_shared'

describe Worker do
  it_behaves_like "a user"
end

我可以rspec spec成功运行。但autotest失败:

Exception encountered: #<ArgumentError: Shared example group 'a user' already exists>

这是因为生成的 rspec 命令行autotest包括user_shared.rb

/usr/local/rvm/rubies/ruby-1.9.2-p290/bin/ruby -rrubygems -S /usr/local/rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/bin/rspec --tty [...] '/path/to/project/spec/models/worker_spec.rb' '/path/to/project/spec/models/user_shared.rb'
Running tests with args ["--color", "--tty", [...], "/path/to/project/spec/models/worker_spec.rb", "/path/to/project/spec/models/user_shared.rb"]...
Done.

Exception encountered: #<ArgumentError: Shared example group 'a user' already exists>

当我'/path/to/project/spec/models/user_shared.rb'从命令行中删除并手动执行它时,它可以工作。

现在,如果我将我的更改user_shared.rb为:

<<< spec/models/user_shared.rb

if !@included then
  @included = true
  shared_examples_for "a user" do
  end
end

它也适用于由 生成的命令行autotest。但这是一个丑陋的解决方法。

既然rspec只知道“*_spec”文件是睾丸,怎么能autotest这样配置呢?

在我的 Gemfile 中,我有以下内容(与测试相关):

<<<< Gemfile

gem 'autotest'
gem 'autotest-rails'

group :test do
  gem 'rspec-rails', '>= 2.6.1'
  gem 'shoulda-matchers'
  gem 'factory_girl_rails', '>= 1.0.2'
  gem 'capybara', '>= 1.0.0'
  gem 'cucumber-rails', '>= 1.0.2'
  gem 'database_cleaner', '>= 0.6.7'
  gem 'spork', '>= 0.9.0.rc'
end
4

1 回答 1

2

自己搞定了……文件夹结构的重组。

  • 创建了新文件夹spec/shared/并将所有示例移到了那里
  • require *_shared.rb从我的示例中删除了任何内容
  • 添加Dir[Rails.root.join("spec/shared/**/*.rb")].each {|f| require f}spec_helper.rb
  • 调整后的自动测试:

.

<<< .autotest

  at.add_mapping(%r%^spec/shared/.*rb%) { |_, _|
    Dir['spec/**/*_spec.rb'] # could be tweaked to just run tests that have this example
                             # but for now I don't care - just run all tests
  }
于 2011-08-31T16:01:41.353 回答