2016-02-26 66 views
2

我正在使用RSpec進行測試。我經常發現很難寫出好的幫手規格。這裏有一個例子:RSpec helper specs mock ActiveRecord

app/helper/time_helper.rb我有以下代碼:

# Returns a text field built with given FormBuilder for given attribute      | ~                          
# (assumed to be a datetime). The field value is a string representation of     | ~                          
# the datetime with current TimeZone applied. 
def datetime_timezone_field(form_builder, attribute) 
    date_format = '%Y-%m-%d %H:%M' 
    datetime = form_builder.object.send(attribute) 
    form_builder.text_field attribute, 
          value: datetime.in_time_zone.strftime(date_format) 
end 

當測試這一點,我需要一個FormBuilder傳遞給方法。我知道如何創建TestView,但我如何創建下面使用的TestModel?在我的規格文件(規格/助理/ time_helper_spec.rb)我有類似:

describe '#datetime_timezone_field' do 
    class TestView < ActionView::Base; end 

    let(:form_builder) do 
    ActionView::Helpers::FormBuilder.new(TestModel.model_name.singular, 
             TestModel.new, 
             TestView.new, 
             {}) 
    end 

    it # Some tests here to check the output... 
end 

我的問題是TestModel。我如何模擬這樣的對象?此幫助程序未連接到我的應用程序中的模型。 TestModel應該是我的應用程序中的「任何模型類」。還是有更好的方法來編寫幫助者方法來擺脫這個問題?

回答

1

你沒有實際測試模型的行爲,無論如何,你只需要,響應你的傳入屬性的對象。

我還以爲你可以做

class TestModel 
    include ActiveModel::Model 

    attr_accessor :whatever_attribute 
end 

您可能不需要全部的ActiveModel,但我不知道表單構建器將會包含哪些部分。你可以隨時看這些。

所以基本上你會然後做

let(:form_builder) do 
    ActionView::Helpers::FormBuilder.new(TestModel.model_name.singular, 
             TestModel.new(whatever_attribute: Time.zone.now), 
             TestView.new, 
             {}) 
end 

我沒有測試這一點,但我看不出有任何理由不應該工作。