gpt4 book ai didi

ruby-on-rails - 如何删除 shoulda 测试中的重复项?

转载 作者:行者123 更新时间:2023-12-02 07:57:17 26 4
gpt4 key购买 nike

这是我的:

   context "Create ingredient from string" do
context "1 cups butter" do

setup do
@ingredient = Ingredient.create(:ingredient_string => "1 cups butter")
end

should "return unit" do
assert_equal @ingredient.unit, 'cups'
end

should "return amount" do
assert_equal @ingredient.amount, 1.0
end

should "return name" do
assert_equal @ingredient.name, 'butter'
end
end
context "1 (18.25 ounce) package devil's food cake mix with pudding" do

setup do
@ingredient = Ingredient.create(:ingredient_string => "1 (18.25 ounce) package devil's food cake mix with pudding")
end

should "return unit" do
assert_equal @ingredient.unit, '(18.25 ounce) package'
end

should "return amount" do
assert_equal @ingredient.amount, 1.0
end

should "return name" do
assert_equal @ingredient.name, 'devil\'s food cake mix with pudding'
end
end
end

显然那里有很多重复。关于如何删除它的任何想法,如果至少是上下文和字符串?

最佳答案

这是针对您的特定问题的解决方案。这个想法是创建一个类方法(如 Shoulda 的 context、setup 和 should)。

将重复封装在一个类方法中,接受所有不同的部分作为参数,如下所示:

def self.should_get_unit_amount_and_name_from_string(unit, amount, name, string_to_analyze)
context string_to_analyze do
setup do
@ingredient = Ingredient.create(:ingredient_string => string_to_analyze)
end

should "return unit" do
assert_equal @ingredient.unit, unit
end

should "return amount" do
assert_equal @ingredient.amount, amount
end

should "return name" do
assert_equal @ingredient.name, name
end
end
end

现在您可以使用一行调用所有这些封装的测试(这里 5 行是为了提高可读性;-)

context "Create ingredient from string" do
should_get_unit_amount_and_name_from_string(
'cups',
1.0,
'butter',
"1 cups butter")
should_get_unit_amount_and_name_from_string(
'(18.25 ounce) package',
1.0,
'devil\'s food cake mix with pudding',
"1 (18.25 ounce) package devil's food cake mix with pudding")
end

在某些情况下,您可能想要接受一个可以作为您的 Shoulda 设置的 block 。

关于ruby-on-rails - 如何删除 shoulda 测试中的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/113275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com