0

在我的规格中尝试使用制造商时,我得到一个空数组。我的猜测是制造商文件尚未加载。如果我在 RSpec 初始化之后加载制造商文件,那么Fabrication::DuplicateFabricatorError会引发 a。这是我的设置:

  • 导轨 4.1.4
  • rspec 核心 3.1.5
  • rspec-rails 3.1.0
  • 制造 2.11.3

.

# config/application.rb
config.generators do |g|
  g.test_framework      :rspec, fixture: true
  g.fixture_replacement :fabrication, dir: "spec/fabricators"
end

# spec/rails_helper.rb
config.fixture_path = "#{::Rails.root}/spec/fabricators"
config.use_transactional_fixtures = true

这是应该工作但不是的代码:

# app/models/user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

# spec/fabricators/user_fabricator.rb
Fabricator(:user) do
  email                 { Faker::Internet.email }
  password              "password"
  password_confirmation "password"
end

# spec/models/user_spec.rb
require 'rails_helper'

describe User do
  before :each do
    @user = Fabricator(:user)
    #=> []
  end

  it "has an email" do
    expect(@user.email).to be_a(String)
    expect(@user.email.length).to be > 0
  end
end

在为我的制造商返回一个空数组后,我在运行 specs: 时收到此错误undefined method 'email' for []:Array:我希望得到一个合格的规格。

4

1 回答 1

4

据我所知,您在这里有两个问题。第一个是你不需要这条线rails_helper.rb

config.fixture_path = "#{::Rails.root}/spec/fabricators"

第二个是您正在调用Fabricator而不是Fabricatebefore规范的块中。Fabricator用于声明定义并Fabricate用于实际创建对象。

于 2014-10-08T14:58:45.520 回答