是否可以先进行一项RSpec测试?

时间:2019-03-17 17:29:06

标签: ruby-on-rails ruby rspec factory-bot

我在测试中使用factory_bot,并希望在运行任何测试之前验证所有工厂。我为这种验证编写了一个测试,并希望它首先运行-在RSpec中这可行吗?

1 个答案:

答案 0 :(得分:0)

Yes it is feasible, see this post: https://thoughtbot.com/blog/testing-your-factories-first. The approach is to create a factories_spec and then add it as a pre-requisite to the rake file.

(1) Create a factories spec file:

 # spec/factories_spec.rb    
FactoryBot.factories.map(&:name).each do |factory_name|
  describe "The #{factory_name} factory" do
    it 'is valid' do
      expect(build(factory_name)).to be_valid
    end
  end
end

(2) To add a pre-requisite to your rake spec:

# Rakefile    
if defined?(RSpec)
  desc 'Run factory specs.'
  RSpec::Core::RakeTask.new(:factory_specs) do |t|
    t.pattern = './spec/factories_spec.rb'
  end
end

task spec: :factory_specs

(3) Run your test with

rake spec