FactoryGirl3, больше не могу получить доступ к фабрикам - PullRequest
0 голосов
/ 29 марта 2012

После обновления до новой FactoryGirl я обновил синтаксис унаследованных фабрик.Теперь я отскакиваю между либо моей фабрикой не определена, либо она двойная.Все ответы, которые я нашел в Интернете, используют более старые версии / синтаксис, и ни одно из предложенных решений действительно не позволяет мне называть свои фабрики.Я прошу прощения за длину файла, и я очень ценю ваше время!Это то, что у меня сейчас, после того, как я боролся с ним некоторое время:

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 'factory_girl'

# 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}

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.include FactoryGirl::Syntax::Methods

  # 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

  def test_sign_in(user)
    sign_in (user)
  end


  # 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
end

фабрики.* FactoryGirl.define do # Sequences sequence :test_name do |n| "Test Name #{n}" end sequence :email do |n| "devnull#{n}@topsailtech.com" end sequence :block_offset do |n| n*100 end sequence :venue_position do |n| n end sequence :sponsorship_position do |n| n end sequence :sponsor_position do |n| n end sequence :id do |n| n end # factories factory :account, :class => Account do id { FactoryGirl.generate(:id) } end factory :invalid_account, :class => Account do id '' end factory :activity, :class => Activity do event { Conference.find_by_name('TechConf') } location { |a| a.event.areas.first } start_time { FactoryGirl.generate(:block_offset) } end_time { FactoryGirl.generate(:block_offset) } title { FactoryGirl.generate(:test_name) } end factory :invalid_activity, :class => Activity do title '' start_time '' event '' end factory :administrator, :class => Administrator do |f| f.email { FactoryGirl.generate(:email) } f.first_name { FactoryGirl.generate(:test_name) } f.last_name { FactoryGirl.generate(:test_name) } f.password 'aBc123xYz!' f.password_confirmation 'aBc123xYz!' end factory :invalid_administrator, :class => Administrator do |f| f.email '' f.first_name '' f.last_name '' f.password 'x' f.password_confirmation 'y' end factory :area, :class => Area do |f| f.event_id { Festival.find_by_name('MusicFest').id } f.name { FactoryGirl.generate(:test_name) } end factory :invalid_area, :class => Area do |f| f.name '' f.event '' end factory :artist, :class => Artist do |f| f.event_id { Festival.find_by_name('MusicFest').id } f.name { FactoryGirl.generate(:test_name) } f.bio 'This artist is really creative.' f.website 'www.topsailtech.com' end factory :invalid_artist, :class => Artist do |f| f.name '' end factory :booth, :class => Booth do |f| f.event_id { Festival.find_by_name('MusicFest').id } f.name { FactoryGirl.generate(:test_name) } end factory :invalid_booth, :class => Booth do |f| f.name '' end factory :category, :class => Category do |f| f.name { FactoryGirl.generate(:test_name) } f.event { Festival.find_by_name('MusicFest') } f.parent { |attrs| attrs.event.categories.first } f.key { |a| a.name.parameterize('') } end factory :invalid_category, :class => Category do |f| f.name '' f.event '' end factory :top_level_category, :class => Category do |f| f.name { FactoryGirl.generate(:test_name) } f.event { Festival.find_by_name('MusicFest') } f.key { |a| a.name.parameterize('') } end factory :conference_session_speaker, :class => ConferenceSessionSpeaker do |f| f.conference_session { ConferenceSession.find_by_title('Giggler') } f.speaker { |a| a.conference_session.event.speakers.first } end factory :invalid_conference_session_speaker, :class => ConferenceSessionSpeaker do |f| end factory :conference_session_without_speaker, :class => ConferenceSession do |f| f.event { Conference.find_by_name('TechConf') } f.location { |a| a.event.venues.first } f.block_date { |a| a.event.start_date } f.start_time { FactoryGirl.generate(:block_offset) } f.end_time { FactoryGirl.generate(:block_offset) } f.title 'Test Title' f.subtitle 'Test Sub-title' f.abstract 'Test abstract blah blah blah' f.track { |a| a.event.tracks.first } end factory :conference_session, :class => ConferenceSession, :parent => :conference_session_without_speaker do |f| f.speaker { |a| a.event.speakers.first } end factory :invalid_conference_session, :class => ConferenceSession do |f| f.event nil f.title '' end factory :conference, :class => Conference do |f| f.account_id { Factory.create(:account).id } f.name { FactoryGirl.generate(:test_name) } f.start_date { Date.today + 1 } f.end_date { Date.today + 3 } f.copyright 'Giggler, Inc.' end factory :invalid_conference, :class => Conference do |f| f.name '' end factory :festival, :class => Festival do |f| f.account_id { Factory.create(:account).id } f.name { FactoryGirl.generate(:test_name) } f.start_date { Date.today + 1 } f.end_date { Date.today + 3 } f.copyright 'Giggler, Inc.' end factory :invalid_festival, :class => Festival do |f| f.name '' end factory :performance, :class => Performance do |f| f.event { Festival.find_by_name('MusicFest') } f.location { |a| a.event.venues.first } f.contributor { |a| a.event.artists.first } f.block_date { |a| a.event.start_date } f.start_time { FactoryGirl.generate(:block_offset) } f.end_time { FactoryGirl.generate(:block_offset) } end factory :invalid_performance, :class => Performance do |f| end factory :series, :class => Series do |f| f.event { Conference.find_by_name('TechConf') } f.location { |a| a.event.venues.first } f.block_date { |a| a.event.start_date } f.start_time { FactoryGirl.generate(:block_offset) } f.end_time { FactoryGirl.generate(:block_offset) } f.title 'Test Title' f.subtitle 'Test Sub-title' f.abstract 'Test abstract blah blah blah' f.track { |a| a.event.tracks.first } end factory :invalid_series, :class => Series do |f| f.title '' end factory :speaker, :class => Speaker do |f| f.event { Conference.find_by_name('TechConf') } f.first_name 'John' f.last_name 'Doe' f.credentials 'Dr.' f.organization 'TechCom' f.title 'Director' f.website 'blahblahblahblahblah.com' f.street_address '123 Foo Road' f.city 'Townsville' f.state 'NC' f.zip_code '27519' f.bio 'Blah blah blah blah blah' end factory :invalid_speaker, :class => Speaker do |f| end factory :sponsor, :class => Sponsor do |f| f.name { FactoryGirl.generate(:test_name) } f.show_logo true f.website 'topsailtech.com' f.sponsorship { Factory.create(:sponsorship) } end factory :invalid_sponsor, :class => Sponsor do |f| f.name '' end factory :sponsorship, :class => Sponsorship do |f| f.name { FactoryGirl.generate(:test_name) } f.position { FactoryGirl.generate(:sponsorship_position) } f.show_logo true f.event { Conference.find_by_name('TechConf') } end factory :invalid_sponsorship, :class => Sponsorship do |f| f.name '' f.position '' f.show_logo '' f.event '' end factory :track, :class => Track do |f| f.event { Conference.find_by_name('TechConf') } f.name { FactoryGirl.generate(:test_name) } end factory :invalid_track, :class => Track do |f| f.event '' f.name '' end factory :vendor, :class => Vendor do association event :factory => :festival, :name => 'MusicFest' category { |a| a.event.categories.first } location { |a| a.event.venues.first } name { FactoryGirl.generate(:test_name) } bio 'They sell things.' website 'www.topsailtech.com' end factory :invalid_vendor, :class => Vendor do |f| f.name '' end factory :venue, :class => Venue do event { Festival.find_by_name('MusicFest') } name test_name street_address '406 Blackwell St.' city 'Durham' state 'NC' zip_code '27701' position venue_position key { |a| a.name.parameterize('') } end factory :invalid_venue, :class => Venue do |f| f.name '' end end контроллер / this_controller_spec.rb

require 'spec_helper'

describe GigViewController do
  include Devise::TestHelpers
  fixtures :all

  render_views

  describe "GET all GigViews" do

    before(:each) do
      @user = user_profile(:doc)
      @event = event(:merlefest)        
    end

    it "should be successful" do
      test_sign_in @user
      get :show, :id => @event.id
      response.should be_success
    end

    **... removed multiple other tests that work but don't use fixtures ...**

    it "should get music" do
      sign_in @user 
      venue = FactoryGirl.create(:venue)
      get :music, :id => @event.id
      response.should be_success
    end

  end
end

Gemfile.lock (отрывок)

factory_girl (3.0.0)
  activesupport (>= 3.0.0)
factory_girl_rails (3.0.0)
  factory_girl (~> 3.0.0)
  railties (>= 3.0.0)
rails (3.1.3)
  actionmailer (= 3.1.3)
  actionpack (= 3.1.3)
  activerecord (= 3.1.3)
  activeresource (= 3.1.3)
  activesupport (= 3.1.3)
  bundler (~> 1.0)
  railties (= 3.1.3)
rspec-rails (2.9.0)
  actionpack (>= 3.0)
  activesupport (>= 3.0)
  railties (>= 3.0)
  rspec (~> 2.9.0)

1 Ответ

0 голосов
/ 03 апреля 2012

Я начал заново, и это то, что я получил до сих пор. Теперь это работает, и я надеюсь, что публикация этого поможет кому-то, пытающемуся начать, как я:

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'
require 'factory_girl_rails'

# 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}

RSpec.configure do |config|

  config.include Devise::TestHelpers, :type => :controller

  # ## 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

  # Use color in STDOUT
  config.color_enabled = true

  # Use color not only in STDOUT but also in pagers and files
  config.tty = true

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

factories.rb

FactoryGirl.define do

  factory :user_profile, :class => UserProfile do
    first_name 'John'
    last_name 'Doe'
    email { "#{first_name}.#{last_name}@example.com".downcase } 
    username 'johndoe'
    password 'johndoe'
    password_confirmation 'johndoe'
    association :account, :factory => :account 
  end

  factory :account, :class => Account do
   # id { FactoryGirl.generate(:id) }
  end

  factory :event, :class => Event do
    name 'Shakori'
    association :account, :factory => :account    
  end 
end

Контроллеры / account_controller.rb

require 'spec_helper'

describe AccountController do
  render_views

  describe "do not GET 'event" do

    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user_profile]
    end

    it "should fail when user is not logged in" do
      get :events
      response.should_not be_success
    end

  end

  describe "GET 'event'" do

    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user_profile]
      sign_in FactoryGirl.create(:user_profile, :username => 'johndoe' )
    end

    it "should be successful, if logged in" do
      get :events 
      response.should be_success
    end

  end


end
...