2016-07-25 48 views
1

我使用FactoryGirl并在建立模型时填充唯一属性。我的型号form的问题是form_type属性只有4种不同的类型可用。所以我每次运行测试时都需要重置sequence。如下所示,我用户before do区块拨打FactoryGirl.reload。但是,我看到一篇文章说FactoryGirl是反模式的。在每次测试之前重置FactoryGirl序列的最佳方法是什么,而不是调用FactoryGirl.reload在每次测试之前重新设定FactoryGirl中序列的正确方法

这里是我的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 

回答

相关问题