Rspec Factory Girl faker不接受专栏



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

规范/模型/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

规范/工厂/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

谢谢

This

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 

您正在使用它作为示例表单,尽管它不是。你没有创建任何对象。不带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

最新更新