Ruby 我怎样才能消除使用预期参数调用方法的断言?
我需要编写一些示例来测试传递给方法的参数 选项#1是将收到的参数作为主题返回,以便验证部分非常简洁:Ruby 我怎样才能消除使用预期参数调用方法的断言?,ruby,rspec,Ruby,Rspec,我需要编写一些示例来测试传递给方法的参数 选项#1是将收到的参数作为主题返回,以便验证部分非常简洁: subject do color = nil pen_double.should_receive(:color=) do |arg| color = arg end color end context ... it { should == 'red' } end context ... it { should == 'green' } end 这个选项的问题
subject do
color = nil
pen_double.should_receive(:color=) do |arg|
color = arg
end
color
end
context ...
it { should == 'red' }
end
context ...
it { should == 'green' }
end
这个选项的问题是“主题”部分太大。当我开始测试其他方法(有很多方法需要测试)时,这就成了一个大问题
选项2不使用“主题”。取而代之的是:
context ...
it { pen_double.should_receive(:color=).with('red') }
end
context ...
it { pen_double.should_receive(:color=).with('green') }
end
显然,现在的“it”部分还不够干燥
是否有我忽略的第三个选项?这其实不是一个不同的选项,但您可以通过提取帮助器方法来改进选项2:
context ...
it { should_be_set_to 'red' }
end
context ...
it { should_be_set_to 'green' }
end
def should_be_set_to(color)
pen_double.should_receive(:color=).with color
end
这是枯燥的,比使用主题块更简洁,并且可以在一定程度上理解,而无需阅读helper方法。(你可能会想出一个比我更好的方法名,因为你知道这个域。)