刚开始学习测试......从字面上开始。 使用rspec-rails,factory_girls_rails和fakers with Rails 4。
我有一个帐户和一个用户模型。有帐户:
has_one :owner, class_name: 'User'
我的第一次模特测试:
## /spec/models/account_spec.rb
require 'rails_helper'
RSpec.describe Account, :type => :model do
it "has a valid factory" do
FactoryGirl.create(:account).should be_valid
end
it "is invalid without a name"
it "is invalid without a subdomain"
it "is invalid without a valid owner"
end
我的2家工厂:
## /spec/factories/accounts.rb
FactoryGirl.define do
factory :account do
name { Faker::Company.name }
subdomain { Faker::Internet.domain_word }
association :owner, factory: :user, strategy: :build
end
end
## /spec/factories/users.rb
FactoryGirl.define do
factory :owner, class: User do
firstname { Faker::Name.first_name }
lastname { Faker::Name.last_name }
email { Faker::Internet.email }
password { Faker::Internet.password(6) }
role {"owner"}
end
end
我的测试返回以下错误:
1) Account has a valid factory
Failure/Error: FactoryGirl.create(:account).should be_valid
ArgumentError:
Factory not registered: user
# /usr/local/rvm/gems/ruby-2.1.1/gems/factory_girl-4.5.0/lib/factory_girl/registry.rb:24:in `find'
# /usr/local/rvm/gems/ruby-2.1.1/gems/factory_girl-4.5.0/lib/factory_girl/decorator.rb:10:in `method_missing'
# /usr/local/rvm/gems/ruby-2.1.1/gems/factory_girl-4.5.0/lib/factory_girl.rb:76:in `factory_by_name'
# /usr/local/rvm/gems/ruby-2.1.1/gems/factory_girl-4.5.0/lib/factory_girl/factory_runner.rb:12:in `run'
# /usr/local/rvm/gems/ruby-2.1.1/gems/factory_girl-4.5.0/lib/factory_girl/strategy/create.rb:5:in `association'
# /usr/local/rvm/gems/ruby-2.1.1/gems/factory_girl-4.5.0/lib/factory_girl/evaluator.rb:31:in `association'
我做错了什么? THX。
答案 0 :(得分:2)
您的帐户工厂正在调用:用户工厂,该工厂不存在。
变化
FactoryGirl.define do
factory :account do
name { Faker::Company.name }
subdomain { Faker::Internet.domain_word }
association :owner, factory: :user, strategy: :build
end
end
到
FactoryGirl.define do
factory :account do
name { Faker::Company.name }
subdomain { Faker::Internet.domain_word }
association :owner, factory: :owner, strategy: :build
end
end