2016-11-11 32 views
2

我有以下問題:RSpec的和工廠女孩 - 錯誤與時間字段

環境:紅寶石:2.3.1和Rails 5.0.0.1

我試圖驗證日期時間字段RSpec和工廠女孩。

我得到這個錯誤:

expected: "2016-11-11 13:30:31 UTC" (From Factory Girl) 
    got: "2016-11-11T13:30:31.218Z" (From database) 

我的代碼:

klass_object = FactoryGirl.create(:字符)

克拉斯=字

RSpec.shared_examples 'API GET #index' do |klass| 
    before { get :index, params: params, accept: Mime[:json] } 


    it "returns a list of #{klass.to_s.underscore.pluralize}" do 
    object_array = json(response.body) 

    klass_attributes = klass.attribute_names.without("id", "created_at", "updated_at").map(&:to_sym) 

    klass_attributes.each do |attribute| 
     object_array.each do |object| 
     expect(object[attribute].to_s).to eq(klass_object[attribute].to_s) 
     end 
    end 
    end 
    ... 
end 

廠:

FactoryGirl.define do 
    factory :character do 
    marvel_id { Faker::Number.number(6).to_i } 
    name { Faker::Superhero.name } 
    description { Faker::Hipster.paragraphs(1) } 
    modified { Faker::Date.between(DateTime.now - 1, DateTime.now) } 

    factory :invalid_character do 
     id '' 
     name '' 
     marvel_id '' 
     modified '' 
    end 
    end 

end

我該如何解決這個問題?

我這樣做,它的工作原理,但我認爲它不太好。有更好的方法來做到這一點?

object_array.each do |object| 
     if ActiveSupport::TimeWithZone == klass_object[attribute].class 
     expect(object[attribute].to_datetime.strftime("%Y-%m-%d %H:%M:%S")).to eq(klass_object[attribute].to_datetime.strftime("%Y-%m-%d %H:%M:%S")) 
     else 
     expect(object[attribute].to_s).to eq(klass_object[attribute].to_s) 
     end 
    end 

感謝您的幫助。

回答

0

嘗試使用to_datetime代替to_s

expect(object[attribute].to_datetime).to eq(klass_object[attribute].to_datetime) 
+0

在這種情況下,我循環每個屬性從類。所以,並非所有的屬性都是日期時間。 –

2

我可以建議你改變你的方法,比較的結果。你可以使用基於金主的想法的方法。

根據此方法,您拍攝一個對象的快照,然後將該對象的所有未來版本與快照進行比較。

在你的情況下,你可以第一次寫json夾具,檢查json是否正確,下次將它與結果json進行比較。

例如

approved.json

[ 
    { 
    "travel_time_seconds": 43200, 
    "available_seats_amount": 10, 
    "departure_at": "2016-04-08T02:00:00.000+03:00", 
    "arrival_at": "2016-04-08T17:00:00.000+03:00", 
    "source_point_name": "New York", 
    "destination_point_name": "Moscow", 
    "tickets_count": 2 
    } 
] 

controller_spec.rb

RSpec.shared_examples 'API GET #index' do |klass| 
    before { get :index, params: params, accept: Mime[:json] } 

    it "returns a list of #{klass.to_s.underscore.pluralize}" do 
    verify(format: :json) { json(response.body).map {|o| o.except('id', 'created_at', 'updated_at' } 
    end 
    ... 
end 

approvals gem,例如,可以幫助ÿ ou與