2

使用guard/spork/rspec/factory_girl 运行rails 3.2.3,并在我的规范助手中包含以下内容:

Spork.prefork do
  ...
  RSpec.configure do |config|
    config.include FactoryGirl::Syntax::Methods
    config.include Devise::TestHelpers, :type => :controller
    ...
  end 
end

并有适当的模型/工厂设置,以便这应该工作:

describe "GET index" do
  describe "as logged in Person without Attendee record" do
    @person = create :person
    sign_in @person
    it "redirects to Attendee new page" do
      visit school_programs_root
      current_path.should == new_school_programs_attendees
    end 
  end 
end 

但是,当我运行规范时,我得到:

Exception encountered: #<NoMethodError: undefined method `create' for #<Class:0x007f860825a798>>

当我将规范的第 3 行更改为:

@person = FactoryGirl.create :person

工厂已创建,但我得到:

Exception encountered: #<NoMethodError: undefined method `sign_in' for #<Class:0x007fcee4364b50>>

所有这些都表明我的控制器规格没有加载助手。

4

2 回答 2

2

Spork 和 FactoryGirl 之间存在与类重新加载相关的已知问题。我多年来使用的围绕此的机制曾经记录在 Spork Wiki 上,但已经消失了(为什么?- 似乎仍然是必要的)。它仍然记录为github 上的 FactoryGirl 问题报告

简单来说:

Gemfile中,关闭 FactoryGirl 的自动要求:

gem 'factory_girl_rails', '~> 3.5.0', require: false

在块中spec_helper.rbeach_run需要 FactoryGirl 并包含语法方法:

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

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

end

这修复了第一个错误。对于第二个错误,即设计错误,您需要sign_in在一个before块内运行,请参阅下面的示例中的修复。那应该对你有用。

describe "GET index" do
  describe "as logged in Person without Attendee record" do
    before do    
      @person = create :person
      sign_in @person
    end

    it "redirects to Attendee new page" do
      visit school_programs_root
      current_path.should == new_school_programs_attendees
    end 
  end 
end 
于 2012-06-25T00:05:48.807 回答
-1

添加到您的规格:

include Devise::TestHelpers
于 2012-04-16T08:30:04.177 回答