对于我的第一个Ruby on Rails引擎--名为**“glossary”**--我希望实现Rspec、ShouldaMatchers、FactoryBot作为测试套件,事情看起来不错,但是FactoryBot一直声称工厂没有注册:
Failures:
1) Glossary::User
Failure/Error: subject {FactoryBot.build(:user)}
ArgumentError:
Factory not registered: user
在开发过程中,rails generate model user first_name last_name user_name
创建了以下文件:
- 应用程序/模型/术语表/用户.rb
- 数据库/迁移/20180731061831_create_glossary_users.rb
- 规格/型号/术语表/user_spec.rb
- 规格/工厂/词汇表_用户.rb
看起来不错。
rails_helper.rb包含以下内容:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'spec_helper'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'shoulda/matchers'
require 'factory_bot_rails'
FactoryBot.definition_file_paths << File.expand_path('../spec/factories', __FILE__)
---
# Fred 2018-07-29: added to engine configuration
Shoulda::Matchers.configure do |config|
config.integrate do |with|
# Choose a test framework:
with.test_framework :rspec
# Choose one or more libraries:
with.library :rails
end
end
# spec/support/factory_bot.rb
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
库/词汇表/engine.rb包含以下内容:
module Glossary
class Engine < ::Rails::Engine
isolate_namespace Glossary
# Fred 2018-07-29: added to engine configuration
config.generators do |g|
g.test_framework :rspec
g.fixture_replacement :factory_bot
g.factory_bot dir: 'spec/factories'
end
end
end
FactoryBot生成此规范/工厂/词汇表_用户.rb文件:
FactoryBot.define do
factory :glossary_user, class: 'Glossary::User' do
first_name "MyString"
last_name "MyString"
user_name "MyString"
end
end
我在spec/models/glossary/user_spec.rb文件中引用了该文件:
require 'rails_helper'
module Glossary
RSpec.describe User, type: :model do
describe 'Validations'
subject {FactoryBot.build(:user)}
it { should validate_presence_of(:user_name) }
end
end
然而,在rails控制台中发出以下命令并不会返回预期的路径,工厂仍然找不到:
Fred:glossary$ rails console
Loading development environment (Rails 5.2.0)
irb(main):001:0> FactoryBot.find_definitions
=> ["/var/www/glossary/spec/dummy/factories", "/var/www/glossary/spec/dummy/test/factories", "/var/www/glossary/spec/dummy/spec/factories"]
irb(main):002:0>
我是否在设置或配置中遗漏了什么?
谢谢你的帮忙!
2条答案
按热度按时间vsnjm48y1#
工厂名称为
glossary_user
,应用作FactoryBot.build(:glossary_user)
zf2sa74q2#
我也遇到过类似的问题,我将代码重新排列为
还有我的测试rb as
因此FactoryBot扫描
FactoryBot.definition_file_paths
中存在的目录,并通过调用FactoryBot.find_definitions
注册所有工厂FactoryBot.find_definitions
调用在以下情况下发生因此,
rails_helper.rb
中语句的顺序很重要编辑2:上述解决方案忽略了其他人指出的工厂使用中的拼写错误