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
是空的。
等一下,我很困惑。我把整數3放到三個'form'模型中。我認爲這是語法。而我沒有通過屬性('form_type')的原因是因爲我認爲在'factory:form do'塊中的'sequence'會自動生成屬性,即使我沒有像你這樣明確地設置它, – JoHksi
我真的從來沒有使用「序列」,所以你可能是對的。儘管如此,你無處給予form_type的價值,比如「Form A」或「Form C」,這顯然是你期望的,所以我認爲你應該考慮改變,因爲它當然沒有被設置。 – user2792268