Rspec厂妹faker不接受专栏

Rspec Factory Girl faker does not accept column

我正在 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

谢谢

您将其用作例如形式,虽然它不是。您没有在那里创建任何对象。在没有 f 的情况下使用它。这就是你的错误 myrailsexp/spec/factories/contacts.rb:5:in block (2 levels) in <top (required)>': 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

这个

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