【问题标题】:FactoryGirl and Devise helpers not working in specsFactoryGirl 和 Devise 助手不符合规范
【发布时间】:2012-04-16 07:33:56
【问题描述】:

使用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>>

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

【问题讨论】:

    标签: ruby-on-rails rspec devise factory-bot


    【解决方案1】:

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

    简而言之:

    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
    

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

    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 
    

    【讨论】:

    • 我不再有这些测试,因此无法测试您对我的代码的建议。感谢您为将来可能使用它的任何人做出贡献。
    【解决方案2】:

    添加到您的规范中:

    include Devise::TestHelpers
    

    【讨论】:

    • 不幸的是没那么简单;虽然它超越了登录错误,但现在它甚至变成了more bizarre
    • 我不确定,但是如果你把 sign_in 放在之前 :each do end block 呢?
    • 没有什么不同。我最终只使用了冗长的语法,并使用 Cucumber 功能进行测试。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多