所以我对RSPEC和Rails来说是新手,我一直在尝试尽可能多地学习RSPEC,我真的很努力地实施包含逻辑的方法的覆盖范围。/p>
我正在使用覆盖范围百分比练习的应用程序,以确保我正确覆盖了我正在实施的代码,并且我缺少对以下方法的覆盖范围:
def initialize_business
businesses.each do |business|
if business.type == 'Restaurant'
@business_type = Business::Restaurant.new(json_directory: 'restaurant.json')
elsif business.type = 'Bar'
@business_type = Business::Bar.new(json_directory: 'bar.json')
else
@business_type = Business::Other.new(json_directory: 'other_business.json')
end
end
business_type = @business_type
initialize_business_creator(business_type)
end
我最初的尝试提供覆盖范围(遗漏了其他无关规格(,但我甚至努力实施任何覆盖范围,因为我对RSPEC太陌生了:
describe '#initialize_business' do
subject do
described_class.new([business], business_sample_file).
initialize_business_creator
end
it 'assigns a value to @business_type' do
expect(assigns(@business_type)).to_not be_nil
end
end
end
我只是在寻找一些有关如何实现这种方法规格的帮助和/或指导。
您需要创建方案来测试代码的分支(
if
,elsif
,else
(
您可以做的是,您可以mock
返回type
的方法以获得所需的结果。
例如,如果要测试评估if
条件并成功运行该分支中的代码。
您可以做这样的事情:
describe '#initialize_business' do
subject do
described_class.new([business], business_sample_file).
initialize_business_creator
end
it 'assigns a value to @business_type' do
expect(assigns(@business_type)).to_not be_nil
end
context "when business type is 'Restaurant'" do
before { allow_any_instance_of(Business).to receive(:type).and_return "Restaurant"
end
it "should create data from restaurant.json" do
//here you can write expectations for your code inside if statement
end
end
end
行:
allow_any_instance_of(business(。接收(:type(。
将返回"餐厅"每当称为business.type
时字符串。
以相同的方式,您可以使此方法返回其他值,例如" bar''并检查您的elsif
方案。