2014-01-18 5 views
2

Я начинаю использовать RSpec, но когда я бегу bundle exec rspec я получаю сообщение об ошибкеRspec неопределенными локальную переменную или метод root_path

/spec/requests/pages_spec.rb:20:in `block (2 levels) in <top (required)>': undefined local 
variable or method `root_path' for #<Class:0x00000102e46850> (NameError) 

У меня нет Spork или Guard работает так под вопрос не следует применять

undefined local variable or method `root_path' (Rspec Spork Guard)

Я добавил config.include Rails.application.routes.url_helpers в моем spec_helper.rb файле, но это не помогло. undefined local variable or method `root_path' Hartl's Tutorial Chapter 5.3.2

Вот pages_spec.rb

require 'spec_helper'                                      

describe "Pages" do                                       
    describe "navigation" do                                     

    def self.it_should_be_on(path_name, value=nil)                               
     before { visit path_name }                                    

     it "should be on #{path_name}" do                                  
     page.should have_link('Home')                                  
     page.should have_link('Inventory')                                 
     page.should have_link('FAQ')                                   
     page.should have_link('About Us')                                 
     page.should have_link('Location')                                 
     page.should have_link('Contact Us')                                 
     # page.should have_link('Login')                                  
     end                                         
    end                                          

    it_should_be_on root_path                                    
    it_should_be_on faq_path                                     
    it_should_be_on about_path                                    
    it_should_be_on location_path                                   
    it_should_be_on contact_path                                    
    # it_should_be_on login_path                                    
    end                                          
end  

spec_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'                         
ENV["RAILS_ENV"] ||= 'test'                                     
require File.expand_path("../../config/environment", __FILE__)                            
require 'rspec/rails'                                      
require 'rspec/autorun'                                      
# Requires supporting ruby files with custom matchers and macros, etc,                          
# in spec/support/ and its subdirectories.                                 
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }                           

# Checks for pending migrations before tests are run.                              
# If you are not using ActiveRecord, you can remove this line.                            
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)                         

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                                      

    # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures                        
    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, remove the following line or assign false                         
    # instead of true.                                       
    config.use_transactional_fixtures = true                                 

    # If true, the base class of anonymous controllers will be inferred                          
    # automatically. This will be the default behavior in future versions of                         
    # rspec-rails.                                        
    config.infer_base_class_for_anonymous_controllers = false                             

    # Run specs in random order to surface order dependencies. If you find an                         
    # order dependency and want to debug it, you can fix the order by providing                        
    # the seed, which is printed after each run.                                
    #  --seed 1234                                       
    config.order = "random"                                     
    config.include Capybara::DSL                                    
    config.include Rails.application.routes.url_helpers                              
end            

Update После прочтения о shared_examples, я попытался это успешно. Есть ли лучший способ написать этот тест? Я в конечном итоге выделение страниц на отдельные страницы, как домашняя страница и т.д.

require 'spec_helper'                

describe "Pages" do                 

    subject { page }                 

    shared_examples "navigation" do |path_name|          
    before { visit send(path_name) }            

    describe "navigation links should be on #{path_name}" do       

     it { should have_link('Home') }            
     it { should have_link('Inventory') }           
     it { should have_link('FAQ') }             
     it { should have_link('About Us') }           
     it { should have_link('Location') }           
     it { should have_link('Contact Us') }           
     # it { should have_link('Login') }            
    end                    
    end                    

    describe "Home Page" do               
    include_examples "navigation", :root_path          
    end                    
end    
+0

Пути не определены на уровне класса в спецификациях – apneadiving

+0

Что значит? Пути не определены в блоке описания навигации? – Patrick

ответ

1

Чтобы сохранить структуру - вы можете изменить код так:

require 'spec_helper'                                      

describe "Pages" do                                       
    describe "navigation" do                                     

    shared_examples_for 'main page' do |path_name|                               
     before { visit send(path_name) }                                    

     it "should be on #{path_name}" do                                  
     page.should have_link('Home')                                  
     page.should have_link('Inventory')                                 
     page.should have_link('FAQ')                                   
     page.should have_link('About Us')                                 
     page.should have_link('Location')                                 
     page.should have_link('Contact Us')                                 
     # page.should have_link('Login')                                  
     end                                         
    end                                          

    it_should_behave_like 'main_page', :root_path                                    
    it_should_behave_like 'main_page', :faq_path                                     
    it_should_behave_like 'main_page', :about_path                                    
    it_should_behave_like 'main_page', :location_path                                   
    it_should_behave_like 'main_page', :contact_path                                    
    # it_should_behave_like 'main_page', :login_path                                    
    end                                          
end  

, потому что «пути не определены на уровне класса в спецификации» (с) Вы не можете вызывать методы пути в классе спецификации. Он должен быть в блоке it. И ваша структура не идеальна. Лучше поместить код в модули, а затем включить его, если вы хотите избежать дублирования.

+0

Я не настроен на сохранение структуры, но я бы хотел избежать дублирования. Вы предложили ввести код в модули, так что будет лучше структура? – Patrick

+0

Отредактировано. Блоки это не очень хорошая идея в такой ситуации. shared_examples_for лучше solutin, как предложил Питер Альфвин =). –

+0

Спасибо за редактирование, я обновил вопрос, чтобы показать решение, которое я получил, прочитав ответы обоих ребят. Похоже, но немного изменил структуру. Что ты думаешь? – Patrick

4

Ни один из помощников Rails не доступны на верхнем уровне describe блока Rspec в. Они доступны только в блоках нижнего уровня (например, let, before, it и т. Д.).

Если вы хотите использовать такой код на примерах, вы можете использовать shared_context или shared_example, как описано в документации RSpec, или переключиться на использование символов в качестве параметров, а на уровне describe и отложить их интерпретацию как до тех пор, пока вы не окажетесь внутри блоков нижнего уровня, как показано в the answer from @IharDrozdov.

+0

Это лучшее объяснение. –

Смежные вопросы