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
应该是我的应用程序中的“任何模型类”。还是有更好的方法来编写帮助者方法来摆脱这个问题?