我正在使用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
由于
答案 0 :(得分:0)
您正在使用它作为例如形式,虽然不是。你没有在那里创建任何对象。在没有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
答案 1 :(得分:0)
此
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