ruby - factory_girl 和 sprintf

标签 ruby factory-bot

首先,我是 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

当然我可以使用 % 符号,但我对此很好奇。

谢谢,

大卫

最佳答案

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

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

这是因为所讨论的代码是从未定义 sprintf 的不同上下文中调用的。

关于ruby - factory_girl 和 sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8262680/

相关文章:

ruby-on-rails - 如何在FactoryGirl中处理外键

ruby-on-rails - Rails - minitest - 测试需要登录的页面

ruby-on-rails - 如何检查 ruby​​ 中属性的类类型?

mysql - ActiveRecord 关联 : am I doing it right?

ruby - 将字符串日期行转换为 Date 对象数组

ruby-on-rails - 在 FactoryBot 上指定所需的字段

sql - rails SQL : How to search on a column in a table ignoring all special characters

ruby - 在 gem 中获取自动加载路径功能

ruby-on-rails - 在 2 个 Rails 应用程序之间共享测试数据

ruby-on-rails - 使用factory_girl中的参数从另一个特征调用特征