【问题标题】:Rspec Factory Girl faker does not accept columnRspec Factory Girl faker 不接受列
【发布时间】:2015-07-27 18:04:18
【问题描述】:

我将 RSpec 与 FactoryGirl 和 Faker 一起使用。我有以下错误:

myrailsexp/spec/factories/contacts.rb:5:in `block (2 levels) in <top (required)>': undefined method `first_name' for #<FactoryGirl::Declaration::Implicit:0x007fa205b233c0> (NoMethodError)

这里是模型app/models/contact.rb:

class Contact < ActiveRecord::Base

  attr_accessible :first_name, :last_name

  validates :first_name, presence: true
  validates :last_name, presence: true

end

spec/models/contact_spec.rb

require 'rails_helper'

RSpec.describe Contact, :type => :model do
  it "has a valid factory" do 
    Factory.create(:contact).should be_valid 
  end
  it "is invalid without a first_name" 
  it "is invalid without a last_name" 
  it "returns a contact's full_name as a string"
end

spec/factories/contacts.rb

require 'faker'

FactoryGirl.define do
  factory :contact do
    f.first_name { Faker::Name.first_name } 
    f.last_name { Faker::Name.last_name }
  end

end

谢谢

【问题讨论】:

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


    【解决方案1】:

    这个

    require 'faker'
    
    FactoryGirl.define do
      factory :contact do
        f.first_name { Faker::Name.first_name } 
        f.last_name { Faker::Name.last_name }
      end
    
    end
    

    应该是

    require 'faker'
    
    FactoryGirl.define do
      factory :contact do |f|
        f.first_name { Faker::Name.first_name } 
        f.last_name { Faker::Name.last_name }
      end
    
    end
    

    还有这一行

    Factory.create(:contact).should be_valid
    

    应该是

    FactoryGirl.create(:contact).should be_valid 
    

    【讨论】:

      【解决方案2】:

      您将其用作例如形式,虽然不是。您没有在那里创建任何对象。在没有f 的情况下使用它。这就是你的错误myrailsexp/spec/factories/contacts.rb:5:in block (2 levels) in &lt;top (required)&gt;': undefined methodfirst_name' for # (NoMethodError)的原因。

      改为这样使用:

      require 'faker'
      
      FactoryGirl.define do
        factory :contact do
          first_name { Faker::Name.first_name } 
          last_name { Faker::Name.last_name }
        end
      
      end
      

      这里使用 FactoryGirl 而不是 Factory。

      require 'rails_helper'
      
      RSpec.describe Contact, :type => :model do
        it "has a valid factory" do 
          FactoryGirl.create(:contact).should be_valid 
        end
        it "is invalid without a first_name" 
        it "is invalid without a last_name" 
        it "returns a contact's full_name as a string"
      end
      

      【讨论】:

        猜你喜欢
        • 2014-01-12
        • 2012-06-12
        • 1970-01-01
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 2015-01-14
        • 2015-05-11
        • 1970-01-01
        相关资源
        最近更新 更多