2013-12-24 4 views
0

Я как бы вытягиваю волосы на этом. Я пытаюсь проверить с помощью rspec и Factory Girl (Ubuntu 13.10 и Rails 4). Кажется, что Rspec не видит ничего из Factory Girl. Вот мой spec_helper.rb:Rpsec и Factory Girl не сотрудничают

# 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 'factory_girl_rails' 
    require 'rspec/rails' 
    require 'rspec/autorun' 
    require 'capybara/rspec' 

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

    ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration) 

    RSpec.configure do |config| 
     config.include FactoryGirl::Syntax::Methods 

     config.use_transactional_fixtures = true 

     config.infer_base_class_for_anonymous_controllers = false 

     config.order = "random" 
     config.color_enabled = true 

     config.tty = true 

     config.formatter = :documentation # :progress, :html, :textmate 
    end 

factories.rb:

FactoryGirl.define do 
     factory :exercise do 
     name 'New Exercise' 
     time 3 
     reps 7 
     weight 12 
     weight_unit 'kg' 
     factory :aerobic_exercise do 
     name 'Jumping Jacks' 
      kind 'Cardio/Aerobic' 
     end 
     factory :bodyweight_exercise do 
      name 'Pushups' 
      kind 'Bodyweight' 
     end 
     factory :cardio_exercise do 
      name 'Jumping Jacks' 
      kind 'Cardio/Aerobic' 
     end 
     factory :lifting_exercise do 
      name 'BB Shoulder Presses' 
      kind 'Weight Lifting' 
     end 
     end 
    end 

и моя неспособность спецификации:

#require 'test/spec' 
    require 'spec_helper' 

    describe Exercise do 
     describe 'Exercise properly normalizes values' do 
     it 'has weight and weight unit if kind is Weight Lifting' do 
      let(:exercise) { FactoryGirl.create(:lifting_exercise) } 
     exercise.should be_weight 
      exercise.time.should be_nil 
     end 
     it 'has time but not weight etc. if kind is Cardio' do 
      let(:exercise) { FactoryGirl.create(:aerobic_exercise) } 
      exercise.should be_time 
      exercise.reps.should be_nil 
     end 
     end 
    end 

Когда я бегу RSpec я получаю эту ошибку:

  Failure/Error: let(:exercise) { FactoryGirl.create(:lifting_exercise) } 
    NoMethodError: 
    undefined method `let' for # <RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x007f2f013b3760> 

HELP! (Пожалуйста)

ответ

2

Метод let не от FactoryGirl, это от Rspec, и проблема в том, что let не должен быть вставлен в пределах it, он предназначен для использования за его пределами.

Учитывая то, как вы написали, я думаю, вы должны просто использовать локальную переменную так:

describe Exercise do 
    describe 'Exercise properly normalizes values' do 
    it 'has weight and weight unit if kind is Weight Lifting' do 
     exercise = FactoryGirl.create(:lifting_exercise) 
     exercise.should be_weight 
     exercise.time.should be_nil 
    end 
    it 'has time but not weight etc. if kind is Cardio' do 
     exercise = FactoryGirl.create(:aerobic_exercise) 
     exercise.should be_time 
     exercise.reps.should be_nil 
    end 
    end 
end 

Кроме того, учитывая, что вы включили FactoryGirl::Syntax::Methods в ваш spec_helper вам не нужно префикс все с FactoryGirl, вы можете просто назвать его так:

exercise = create(:lifting_exercise)

Я надеюсь, что помогает!

-Chad

+0

Спасибо, связка. Сначала я использовал что-то принципиально идентичное этому, только я думаю, что вместо «FactoryGirl.create» вместо «FactoryGirl.create» я использовал «Factory.create» (думаю, я выбрал это из некоторого устаревшего учебника?) И только изменил его на «let 'синтаксис после того, что я Googled вверх, казалось, предлагал это. Я предположил, что я неправильно понял, ваше решение решило проблему. Еще раз спасибо! – Joeman29

+0

'let (: exercise) {FactoryGirl.create (: lift_exercise)}' будет работать, если вы ставите его перед всеми его методами – DenniJensen

1

Ваш вопрос не RSpec и FactoryGirl не играет хорошо вместе.

let не входит в группу методов примера. Обратите внимание, что у вас есть let внутри блока it. Это должно работать

#require 'test/spec' 
require 'spec_helper' 

describe Exercise do 

    describe 'Exercise properly normalizes values' do 

    context 'with a lifting exercise' do 
     let(:exercise) { FactoryGirl.create(:lifting_exercise) } 

     it 'has weight and weight unit if kind is Weight Lifting' do 
     exercise.should be_weight 
     exercise.time.should be_nil 
     end 

    end 

    context 'with an aerobic exercise' do 
     let(:exercise) { FactoryGirl.create(:aerobic_exercise) } 

     it 'has time but not weight etc. if kind is Cardio' do 
     exercise.should be_time 
     exercise.reps.should be_nil 
     end 

    end   

    end 

end 

Примечаниеcontext это просто псевдоним для describe.

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