Factory_girl and sprintf

First of all, I'm pretty new to Ruby, although I have a strong background in Java (not helping here :). I created my first Rails application and I use FactoryGirl. I stumbled upon something strange (for me) and I can’t understand why he is behaving this way.

Using sprintf in a factory (see last test) causes the following error:

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)>' 

Here is the complete specification demonstrating this behavior:

 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 

Of course, I could use the% notation, but I'm really interested.

Thanks,

David

+4
source share
1 answer

You need to access sprintf using its full namespace:

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

This is because the code being called is called from a different context where sprintf is undefined.

+6
source

Source: https://habr.com/ru/post/1382961/


All Articles