factory_girl and sprintf

4
首先,我对Ruby还不太熟悉,尽管我在Java方面有很强的背景(这里并没有帮上忙:)。我创建了我的第一个Rails应用程序,并使用FactoryGirl。我遇到了一些奇怪的事情(对我来说),我无法弄清楚为什么它会表现出这样的行为。
在工厂内使用sprintf(请参见最后一个测试)会引发以下错误:
Failures:
  1) Test raises an ArgumentError
     Failure/Error: sprintf('Product %05d', n)
     ArgumentError:
       wrong number of arguments (3 for 2)
     # ./spec/models/fg_spec.rb:6:in `fff'
     # ./spec/models/fg_spec.rb:31:in `block (3 levels) in <top (required)>'
     # ./spec/models/fg_spec.rb:62:in `block (2 levels) in <top (required)>'

以下是完整规范,展示了这种行为:

def fff(n)
    sprintf('WWW Product %05d', n)
end

b1 = proc { |n| fff(n) }
b2 = proc { |n| sprintf('WWW Product %05d', n) }

FactoryGirl.define do

    factory :product1, :class => Product do
        sequence(:name) { |n| 'Product %05d' % "#{n}" }
    end

    factory :product2, :class => Product do
        sequence(:name) { |n| sprintf('WWW Product %05d', n) }
    end

    factory :product3, :class => Product do
        sequence(:name, 1, &b1)
    end

    factory :product4, :class => Product do
        sequence(:name, 1, &b2)
    end

    factory :product5, :class => Product do
        sequence(:name) { |n| fff(n) }
    end

end

describe Test do

    it "works with %" do
        p = Factory.create(:product1)
        puts p.inspect
    end

    it "does not work with sprintf" do
        expect { Factory.create(:product2) }.to raise_error(ArgumentError)
    end

    it "works with a block with a function" do
        p = Factory.create(:product3)
        puts p.inspect
    end

    it "works with a block with sprintf" do
        p = Factory.create(:product4)
        puts p.inspect
    end

    it "does not work with a function with sprintf" do
        expect { Factory.create(:product5) }.to raise_error(ArgumentError)
    end

end

当然,我可以使用%符号,但我对此非常好奇。
谢谢,
David
1个回答

6

您需要使用sprintf的完整名称空间进行访问:

b2 = proc { |n| Kernel.sprintf('WWW Product %05d', n) }

这是因为所涉及的代码在不同的上下文中被调用,导致sprintf未定义。

谢谢,可以了;我以为Kernel总是在范围内的......就像Java中不需要导入java.lang.*一样;奇怪 :) - ddidier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接