加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – factory_girl和sprintf

发布时间:2020-12-17 03:01:40 所属栏目:百科 来源:网络整理
导读:首先,我对 Ruby很新,虽然我有很强的Java背景(没有帮助:).我创建了我的第一个Rails应用程序,我正在使用FactoryGirl.我遇到了一些奇怪的东西(对我来说),我无法弄清楚为什么它会像这样. 在工厂中使用sprintf(请参阅上一个测试)会引发以下错误: Failures: 1) Te
首先,我对 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,&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

当然我可以使用%表示法,但我对此非常好奇.

谢谢,

大卫

解决方法

您需要使用其完整命名空间访问sprintf:

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

这是因为有问题的代码是在未定义sprintf的不同上下文中调用的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读