我是ruby和RSpec的新手,我尝试模拟将输入时间转换为本地时间的函数,但是我真的不知道如何实现它。我想我需要嘲笑一切,但我不知道该怎么做。谁能帮我吗?
def proposal_local_time(input_time)
return I18n.t('shared.proposals.proposal_header.placeholder') unless input_time.respond_to?(:strftime)
input_time.utc.localtime.to_s(:short)
end
我写的测试:
describe '#proposal_local_time' do
subject {proposal_local_time(input_time)}
let(:input_time) { double('input_time') }
let(:local_time) {'local_time'}
before do
allow(input_time).to receive_message_chain(:utc, :localtime, :to_s).and_return(local_time)
end
context 'when the input time is invalid' do
let(:input_time) {'invalid input'}
it { is_expected.to eq(I18n.t('shared.proposals.proposal_header.placeholder')) }
end
context 'when the input time is valid' do
it { is_expected.to eq(local_time) }
end
end
例如,如果您使用此方法:
class Foo
def some_method(input_time)
local_time = proposal_local_time(input_time)
# do something with local_time
return true if local_time
end
def proposal_local_time(input_time)
return I18n.t('shared.proposals.proposal_header.placeholder') unless input_time.respond_to?(:strftime)
input_time.utc.localtime.to_s(:short)
end
end
您可以像这样编写规格模拟proposal_local_time
:
describe 'Foo' do
subject { Foo.new }
let(:local_time) { double("local_time") }
let(:input_time) { double("input_time") }
before(:each) do
# mock proposal_local_time
allow_any_instance_of(Foo).to receive(:proposal_local_time).with(input_time).and_return(local_time)
end
it "tests #some_method" do
expect(subject.some_method(input_time)).to be true
end
end
当然,这只是示例,您必须根据实际代码来更改/调整规格/代码。您也必须单独测试proposal_local_time
,但是如果要针对特定的上下文进行模拟的话。