rspec 3,capybara和machinist 2的问题

时间:2014-09-06 17:03:18

标签: capybara rspec-rails machinist

我有此功能测试(商店模型具有唯一性验证):

feature "Index" do
  before do
    3.times { Store.make! }
  end
  scenario "User visit index" do
    visit stores_path
     within("table.table") do
       Store.all.each do |store|
         expect(page).to have_content(store.name)
       end
     end
   end
end

当我运行测试时,随机失败:

Failure/Error: 3.times { Store.make! }
 ActiveRecord::RecordInvalid:
   Validation failed: name has already been taken

我的蓝图是(按照机械师文档生成一个独特的记录):

Store.blueprint do
  name { "store #{sn}" }
end

我使用DatabaseCleaner gem,然后使用我的配置rails_spec:

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'shoulda/matchers'
require 'capybara/rails'
require 'capybara/rspec'
require 'pundit/rspec'
require 'database_cleaner'

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

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|

  config.mock_with :rspec
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false


  config.before(:each) do |example|
    DatabaseCleaner.strategy = if example.metadata[:js]
      :truncation
    else
      :transaction
    end
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

  DatabaseCleaner.logger = Rails.logger

  config.infer_spec_type_from_file_location!

这些错误让我发疯了

1 个答案:

答案 0 :(得分:0)

尝试在spec/spec_helper.rb中替换以下内容:

config.before :suite do |example|
  DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction
end

config.before do
  DatabaseCleaner.clean
end