NameError: неинициализированная константа в приложении Rails при тестировании с RSpec и Spork - PullRequest
3 голосов
/ 18 декабря 2010

Я пытаюсь запустить свои тесты в моем первом приложении Rails, используя следующую команду в Терминале:

rspec spec/

Но это приводит только к следующим ошибкам:

Exception encountered: #<NameError: uninitialized constant PagesController>
backtrace:
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-expectations-2.3.0/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'
/Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/monkey/spork/test_framework/rspec.rb:4:in `run_tests'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:13:in `block in run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:21:in `block in initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `fork'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `new'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/server.rb:47:in `run'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1558:in `perform_without_block'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1518:in `perform'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1592:in `block (2 levels) in main_loop'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1588:in `loop'

Я могу успешно запустить сайт в браузере, и "Spork готов и слушает", что заставляет меня думать, что есть проблема с Gems, которые я использую, RSpec, Spork или ... что-то?Вместо того, чтобы тесты, которые я написал как тесты PagesController и RSpec, были основаны на книге RailsTutorial.org.Я в растерянности.

Вот мой Gemfile:

source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
gem 'gravatar_image_tag', '0.1.0'
gem "nokogiri", '1.4.4'
gem 'will_paginate', '3.0.pre2'

group :development do
  gem 'rspec-rails', '2.3.0'
  gem 'annotate-models', '1.0.4'
  gem 'faker', '0.3.1'
end

group :test do
  gem 'rspec', '2.3.0'
  gem 'webrat', '0.7.1'
  gem 'spork', '0.9.0.rc2'
  gem 'factory_girl_rails', '1.0'
end

Вслед за моим локальным списком драгоценных камней:

abstract (1.0.0)
actionmailer (3.0.3)
actionpack (3.0.3)
activemodel (3.0.3)
activerecord (3.0.3)
activeresource (3.0.3)
activesupport (3.0.3)
annotate-models (1.0.4)
arel (2.0.6)
autotest (4.3.2)
autotest-fsevent (0.2.2)
autotest-growl (0.2.4)
autotest-rails-pure (4.1.0)
builder (2.1.2)
bundler (1.0.3)
diff-lcs (1.1.2)
erubis (2.6.6)
factory_girl (1.3.2)
factory_girl_rails (1.0)
faker (0.3.1)
gravatar_image_tag (0.1.0)
i18n (0.5.0)
mail (2.2.12)
mime-types (1.16)
nokogiri (1.4.4)
polyglot (0.3.1)
rack (1.2.1)
rack-mount (0.6.13)
rack-test (0.5.6)
rails (3.0.3)
railties (3.0.3)
rake (0.8.7)
rdoc (2.5.11)
rspec (2.3.0)
rspec-core (2.3.0)
rspec-expectations (2.3.0)
rspec-mocks (2.3.0)
rspec-rails (2.3.0)
spork (0.9.0.rc2)
sqlite3-ruby (1.2.5)
sys-uname (0.8.4)
thor (0.14.6)
treetop (1.4.9)
tzinfo (0.3.23)
webrat (0.7.1)
will_paginate (3.0.pre2)

У кого-нибудь есть идеи или я могу помочь?предоставляя больше информации?Я новичок в Rails, возвращаюсь к нему время от времени и, кажется, сталкиваюсь с проблемами, прежде чем снова сдаться ...

Обновление Мой файл Spec / spec_helper.rb:

require 'rubygems'
require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However, 
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  unless defined?(Rails)
    require File.dirname(__FILE__) + "/../config/environment"
  end
  require 'rspec/rails'

  # Requires supporting files with custom matchers and macros, etc,
  # in ./support/ and its subdirectories.
  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  Rspec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, comment the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    ### Part of a Spork hack. See http://bit.ly/arY19y
    # Emulate initializer set_clear_dependencies_hook in 
    # railties/lib/rails/application/bootstrap.rb
    ActiveSupport::Dependencies.clear
  end
end

Spork.each_run do
end

А вот вывод из терминала при удалении содержимого spec_helper:

No DRb server is running. Running in local process instead ...
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing': uninitialized constant Object::PagesController (NameError)
    from /Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:44:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:10:in `block in autorun'

Ответы [ 3 ]

6 голосов
/ 20 декабря 2010

Оказалось, что проблема была вызвана неправильным правилом проверки в другой модели. Потребовалось много случайных мыслей и попыток, но в конце концов они оказались без особой помощи из сообщения об ошибке.

1 голос
/ 11 сентября 2015

Если у вас есть эта проблема на рейках 3.2 с установкой Spork, то вот что вам нужно сделать.

После запуска spork rspec --bootstrap откройте файл spec_helper.rb.

Вы должны увидеть что-то вроде этого:

require 'rubygems'
require 'spork'
#uncomment the following line to use spork with the debugger
#require 'spork/ext/ruby-debug'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.

end

Spork.each_run do
  # This code will be run each time you run your specs.

end

# --- Instructions ---
# Sort the contents of this file into a Spork.prefork and a Spork.each_run
# block.
#
# The Spork.prefork block is run only once when the spork server is started.
# You typically want to place most of your (slow) initializer code in here, in
# particular, require'ing any 3rd-party gems that you don't normally modify
# during development.
#
# The Spork.each_run block is run each time you run your specs.  In case you
# need to load files that tend to change during development, require them here.
# With Rails, your application modules are loaded automatically, so sometimes
# this block can remain empty.
#
# Note: You can modify files loaded *from* the Spork.each_run block without
# restarting the spork server.  However, this file itself will not be reloaded,
# so if you change any of the code inside the each_run block, you still need to
# restart the server.  In general, if you have non-trivial code in this file,
# it's advisable to move it into a separate file so you can easily edit it
# without restarting spork.  (For example, with RSpec, you could move
# non-trivial code into a file spec/support/my_helper.rb, making sure that the
# spec/support/* files are require'd from inside the each_run block.)
#
# Any code that is left outside the two blocks will be run during preforking
# *and* during each_run -- that's probably not what you want.
#
# These instructions should self-destruct in 10 seconds.  If they don't, feel
# free to delete them.

Измените содержимое файла на это:

require 'rubygems'
require 'spork'

Spork.prefork do

  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'


  RSpec.configure do |config|
    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
end

Spork.each_run do

end

Это должно исправить твои проблемы.


Еще одна вещь, которую стоит отметить, это то, что вы не можете использовать rspec 3.0+ со spork. Spork не поддерживается и используется только для унаследованных рельсовых приложений, которые зависят от ruby ​​1.9.2 или менее. Если ваше приложение поддерживает ruby ​​1.9.3+, взгляните на spring .

0 голосов
/ 22 января 2011

как было написано в рельсах урок "spork" иногда "зависает" так: перезапустите "spork"

...