2016-07-24 68 views
1

我正在使用Rspec在Form模型上編寫controller_spec_test。我使用FactoryGirl來生成模型。當我在form_controller_spec中運行單個測試時,它們都通過了。但是,當我運行整個文件時,我看到所有測試都失敗,並且錯誤消息是ActiveRecord::RecordInvalid: Validation failed: Form type can't be blank工廠女孩沒有正確設置屬性

這裏是我的forms.rb Factorygirl文件, FactoryGirl.define做

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 
      @forms = forms 
     end 

     it "loads all of the forms into @forms" do 
      get :index 
      expect(assigns(:forms)).to match_array(@forms) 
     end 
    end 

end 

我不明白,個別測試正在通過但當我運行整個文件時,測試失敗。而且我也不知道爲什麼form_type是空的。

回答

0

您:form_attributes方法缺少一個適當的值:FORM_TYPE

let(:form_attributes) { 
    FactoryGirl.attributes_for(:form, "Form C", user: @current_user) 
} 

儘管也似乎無法讓你的心,你是否希望字符串或整數,如上面的號召let(:forms)你已經傳入了整數3.這是一個不一致,可能需要以某種方式修復。

+0

等一下,我很困惑。我把整數3放到三個'form'模型中。我認爲這是語法。而我沒有通過屬性('form_type')的原因是因爲我認爲在'factory:form do'塊中的'sequence'會自動生成屬性,即使我沒有像你這樣明確地設置它, – JoHksi

+0

我真的從來沒有使用「序列」,所以你可能是對的。儘管如此,你無處給予form_type的價值,比如「Form A」或「Form C」,這顯然是你期望的,所以我認爲你應該考慮改變,因爲它當然沒有被設置。 – user2792268