Rspec使用开发数据库

时间:2015-09-11 12:56:08

标签: ruby-on-rails rspec ruby-on-rails-4.2

我使用Rails 4.2和Ruby 2.2以及rspec作为测试用例。我已经设置了

Rails.env = 'test'

在我的spec_helper和rails_helper中。这是我的database.yml文件:

development:
  adapter: postgresql
  encoding: unicode
  database: app_dev
  pool: 5
  username: postgres
  password: root

test:
  adapter: postgresql
  encoding: unicode
  database: app_test
  pool: 5
  username: postgres
  password: root

production:
  adapter: postgresql
  encoding: unicode
  database: app_prod
  pool: 5
  username: postgres
  password: root

这是我的rails_helper:

Rails.env = 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.include JsonHelper
  config.include PathHelper
  config.include S3Helper
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
end

application.rb中:

require File.expand_path('../boot', __FILE__)

require 'rails/all'
require 'yaml'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module AppName
  class Application < Rails::Application
    config.generators do |g|
      g.assets = false
      g.helper = false
      g.views = false
    end

    # Load all locale files
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
    config.i18n.load_path += Dir[Rails.root.join(
                              'config', 'locales', '**', '**', '*.{rb,yml}')]
    config.autoload_paths += %W(#{config.root}/lib)
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    config.autoload_paths += Dir["#{config.root}/app/workers/"]
    config.action_controller.include_all_helpers = false
    config.active_record.schema_format           = :sql
    config.i18n.available_locales = [:en, :hi, :mr]
    config.i18n.default_locale = :hi
    config.i18n.fallbacks = [:en]
    config.active_record.raise_in_transactional_callbacks = true
  end
end

的Gemfile:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.0'

# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18.2'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# Turbolinks makes following links in your web application faster
gem 'turbolinks', '~> 2.5.3'

# Use Unicorn as the app server
gem 'unicorn', '~> 4.9.0'

# Use jquery as the JavaScript library
gem 'jquery-rails', '~> 4.0.4'

# Integrate the jQuery Validation plugin into the Rails asset pipeline
gem 'jquery-validation-rails', '~> 1.13.1'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'

# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# use swagger for api documentation
gem 'swagger-docs', '~> 0.1.9'

# for consuming restful web services
gem 'httparty', '~> 0.13.5'

# for ActiveRecord model/data translations
gem 'globalize', '~> 5.0.0'

# generates accessors for translated fields
gem 'globalize-accessors', '~>0.2.1'

# Amazon Web service SDK Ruby
gem 'aws-sdk', '~> 2.1.0'

# cloud services for S3
gem 'fog', '~> 1.33.0'

# handle file uploads
gem 'carrierwave', '~>0.10.0'

# Photo Resizing
gem 'mini_magick', '~> 4.2.7'

# Background Jobs
gem 'sidekiq', '~> 3.4.2'

# Geocoder
gem 'geocoder', '~> 1.2.9'

# active admin
gem 'activeadmin', '~> 1.0.0.pre1'

# for authentication
gem 'devise', '~> 3.5.1'

# for roles of active admin
gem 'rolify', '~> 4.0.0'

# for authorization
gem 'cancan', '~> 1.6.10'

group :development, :test do
  # Debugging using pry
  gem 'pry-rails', '~> 0.3.4'
  gem 'pry-byebug', '~> 3.1.0'

  # testing framework for rails
  gem 'rspec-rails', '~> 3.1.0'
  gem 'rspec-collection_matchers', '~> 1.1.2'
  gem 'factory_girl_rails', '~> 4.4.1'
  gem 'shoulda-matchers', '~> 2.8.0'

  # code test coverage
  gem 'simplecov', '~> 0.7.1'
  gem 'simplecov-rcov', '~> 0.2.3'
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # speeds up development by keeping your application running in the background
  gem 'spring', '~> 1.3.6'
end

group :development do
  # generates ER diagrams for rails application
  gem 'rails-erd', '~> 1.4.1'
end

group :test do
  # set of strategies for cleaning your database
  gem 'database_cleaner', '~> 1.3.0'
end

当我运行我的测试用例时,Rails.env正在测试&#39;正如预期的那样(使用pry验证)。 但是我的测试用例总是在开发数据库中。

Rails.env
#=> "test"

ActiveRecord::Base.connection_config
#=> {:adapter=>"postgresql", :encoding=>"unicode", :database=>"app_dev", :pool=>5, :username=>"postgres", :password=>"root"}

spec_helper:

require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'simplecov'
require 'simplecov-rcov'
require 'database_cleaner'
require 'factory_girl_rails'

ENV['RAILS_ENV'] ||= 'test'
SimpleCov.start

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  # Database Cleaner
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
    Rails.application.load_seed
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

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

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end

SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
自从过去几个小时以来,我一直在挠头,但似乎没有什么可以解开这个谜团。任何帮助都会很棒!

6 个答案:

答案 0 :(得分:7)

听起来好像环境中的某个地方(可能是您的宝石之一),它将您的环境设置为dev或建立与dev数据库的连接。

要显式连接到测试数据库,请添加:

ActiveRecord::Base.establish_connection

到你的rails_helper。

麻烦制造者的主要候选人将是'gem'trail-erd','〜&gt; 1.4.1' 。如果您在迁移时自动生成图表,则在迁移测试模式时,它将连接到dev数据库以转储图表。

尝试删除此gem或'.rake'文件,看看会发生什么。

答案 1 :(得分:5)

你的rails_helper看起来很奇怪。第一行说:

Rails.env = 'test'

在第一行你还没有加载Rails(我想你使用bundle exec rspec运行RSpec)。所以它应该引发一个错误。

因此我在rails_helper中做了一些小改动:

require File.expand_path('../../config/environment', __FILE__)
Rails.env = 'test'
require 'spec_helper'
require 'rspec/rails'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

# the rest

现在放

expect(ActiveRecord::Base.connection_config[:database]).to match(/test/)

在你的规范的某个地方,应该成功通过。

答案 2 :(得分:2)

您的测试进入开发数据库的原因是您在环境中的某处定义了ENV['DATABASE_URL']

有两种方法可以指定要使用的数据库连接:

  1. 指定ENV['DATABASE_URL']
  2. 使用非常受欢迎的database.yml文件
  3. 在许多情况下,第一个优先于后者。

    我意识到在使用ENV [&#39; DATABASE_URL&#39;]设置我的生产数据库后,我遇到了类似于你的问题,但却发现我的所有环境(测试和开发)突然开始使用我的生产数据库,无论database.yml中的内容如何。

    要解决我的问题,我所做的只是将环境变量上的名称更改为其他内容,以便它不再覆盖我的database.yml配置。

    阅读本文将解决您的问题:Connection Preference information

答案 3 :(得分:1)

1)将require: false添加到'rails-erd'gem的声明

gem 'rails-erd', '~> 1.4.1', require: false

2)在 spec_helper.rb 中,将Rails.env = 'test'替换为ENV['RAILS_ENV'] ||= 'test'

3)在您的 bin / rspec (如果有)中验证您没有任何指令更改env

的值

4)然后从命令行停止弹簧

spring stop

5)从命令行运行您的规范

rspec

答案 4 :(得分:1)

您可以使用RAILS_ENV=test bundle exec rspec spec

运行rspc

你也可以放在rails_helper.rb

里面
Rails.env = 'test'

还将测试框架部分从开发测试移到gemfile

内的测试
group :test do
  # testing framework for rails
  gem 'rspec-rails', '~> 3.1.0'
  gem 'rspec-collection_matchers', '~> 1.1.2'
  gem 'factory_girl_rails', '~> 4.4.1'
  gem 'shoulda-matchers', '~> 2.8.0'

  # set of strategies for cleaning your database
  gem 'database_cleaner', '~> 1.3.0'
end

答案 5 :(得分:0)

我的答案适用于在Rails之外将Rspec与Ruby一起使用的任何人。例如,假设您正在创建Ruby gem。好了,您仍然可以在项目的config文件夹中添加database.yml并指定测试选项:

{
          "tags" => [
        [0] "_grokparsefailure"
    ],
          "host" => "rolf-PE-860",
      "@version" => "1",
          "type" => "lmc",
    "@timestamp" => 2018-06-26T23:41:49.349Z
}
{
          "tags" => [
        [0] "_grokparsefailure"
    ],
          "host" => "rolf-PE-860",
      "@version" => "1",
          "type" => "lmc",
    "@timestamp" => 2018-06-26T23:41:49.355Z
}

现在,您可以在spec_helper.rb中添加以下内容:

test:
  adapter: 'mysql2'
  encoding: utf8mb4
  collation: utf8mb4_bin
  pool: 1
  username: root
  password:
  host: localhost
  database: 'my_site_test'

:suite范围指示代码块应在测试套件之前运行一次,这意味着您要进行所有测试。