【问题标题】:Factory_Girl + RSpec: undefined method 'create' when create(:user)Factory_Girl + RSpec:创建(:用户)时未定义的方法“创建”
【发布时间】:2023-04-05 14:58:02
【问题描述】:

不能调用“dummy = create(:user)”来创建用户。来回走了几个小时。

/home/parreirat/backend-clone/Passworks/spec/models/user_spec.rb:15:in `block (2 levels) in <top (required)>': undefined method `create' for #<Class:0xbcdc1d8> (NoMethodError)"

这是工厂,users.rb:

FactoryGirl.define do

    factory :user do
      email 'heheheheheheh@gmail.com'
      password 'chucknorris'
      name 'luis mendes'
    end

end

这就是我在 user_spec.rb 中调用 FactoryGirl 的方式:

require 'spec_helper'

describe 'User system:' do

 context 'registration/login:' do

    it 'should have no users registered initially.' do
      expect(User.count).to eq(0)
    end

    it 'should not be logged on initially.' do
      expect(@current_user).to eq(nil)
    end

    dummy = create(:user)

    it 'should have a single registered user.' do
      expect(User.count).to eq(1)
    end

  end

end

我按照说明将其添加到 spec_helper.rb 中:

RSpec.configure do |config|

   # Include FactoryGirl so we can use 'create' instead of 'FactoryGirl.create'
   config.include FactoryGirl::Syntax::Methods

end

【问题讨论】:

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


    【解决方案1】:

    您需要将 create 行移到正在使用的规范中:

    it 'should have a single registered user.' do
      dummy = create(:user)
      expect(User.count).to eq(1)
    end
    

    现在,该行没有上下文(不在规范中,也不在 before 块中)。这可能就是您收到错误的原因。你可能所有的设置都是正确的,但只是在错误的地方有一行。

    【讨论】:

    • 哇,成功了。但为什么?什么原因?它到底有什么区别,在它的内部和外部?谢谢!
    • @GigaBass:我没有仔细查看 FactoryGirl 源代码,但我猜测这些方法(createattributes_for 等)仅在测试或规范中公开.你把它放在你的测试文件中的位置有点不着边际,所以这些方法不可用。有道理?如果答案正确,请采纳。
    【解决方案2】:

    获得undefined method 'create' 错误的另一个原因可能是您在spec/support/factory_girl.rb 中缺少此配置:

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

    我找到了代码here

    【讨论】:

    • 另外,不要忘记像这样从 rails_helper.rb 要求它:require 'support/factory_bot'。仅供参考:FactoryGril 现在更名为 FactoryBot。
    【解决方案3】:

    有时您只需要在测试文件的顶部输入require 'rails_helper'。这解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      相关资源
      最近更新 更多