我正在使用FactoryGirl并在制作模型时填充唯一属性。我的模型form
的问题在于form_type
属性只有4种不同的类型可用。所以我每次运行测试时都需要重置sequence
。如下所示,我使用before do
阻止来呼叫FactoryGirl.reload
。但是,我看到一篇文章称这是FactoryGirl的反模式。在每次测试之前,在FactoryGirl中重置序列而不是调用FactoryGirl.reload
的最佳方法是什么?
这是我的forms.rb
Factorygirl文件,
FactoryGirl.define do
factory :form do
association :user
sequence :form_type do |n|
Form.form_types.values[n]
end
end
end
这是我的form.rb模型文件:
class Form < ActiveRecord::Base
belongs_to :user, required: true
enum form_types: { :a => "Form A", :b => "Form B", :c => "Form C", :d => "Form D"}
validates :form_type, presence: true
validates :form_type, uniqueness: {scope: :user_id}
end
这是我的forms_controller_spec.rb文件:
require 'rails_helper'
RSpec.describe FormsController, type: :controller do
login_user
let(:form) {
FactoryGirl.create(:form, user: @current_user)
}
let(:forms) {
FactoryGirl.create_list(:form , 3, user: @current_user)
}
let(:form_attributes) {
FactoryGirl.attributes_for(:form, user: @current_user)
}
describe "GET #index" do
before do
FactoryGirl.reload
end
it "loads all of the forms into @forms" do
get :index
expect(assigns(:forms)).to match_array(@forms)
end
end
end
答案 0 :(得分:0)
这个问题可能有所帮助。