问题
I'm going to test the model concern get_uniq_id method.
app/models/concerns/id_generation.rb
module IdGeneration
extend ActiveSupport::Concern
module ClassMethods
def get_uniq_id
id = ''
loop {
id = generate_id
break unless Ticket.find_by_token(id)
}
id
end
def generate_id
id = []
"%s-%d-%s-%d-%s".split('-').each{|v| id << (v.eql?('%s') ? generate_characters : generate_digits)}
id.join('-')
end
def generate_digits(quantity = 3)
(0..9).to_a.shuffle[0, quantity].join
end
def generate_characters(quantity = 3)
('A'..'Z').to_a.shuffle[0, quantity].join
end
end
end
spec/concerns/id_generation_spec.rb
require 'spec_helper'
describe IdGeneration do
class Dummy
include IdGeneration::ClassMethods
end
subject { Dummy.new }
it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
end
It throws up the error:
Failure/Error: it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
NameError:
undefined local variable or method `get_uniq_id' for #<RSpec::ExampleGroups::IdGeneration:0x00000001808c38>
If I specify the subject explicitly it { should subject.get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/)
}. It works.
Do I need specify the subject explicitly?
回答1:
The way you're calling the method - yes. The method needs to be called on object. In this case, the get_uniq_id
will be executed in context of currently running test, and this is why the error pops up.
The shortcut you can use might be like:
it { should respond_to :get_uniq_id }
Which will perform test similar to subject.respond_to?(:get_uniq_id)
. The method call however, needs explicit receiver.
You can update your test in order to use it as in your example, if you modify it slightly:
require 'spec_helper'
describe IdGeneration do
class Dummy
include IdGeneration::ClassMethods
end
subject { Dummy.new }
def get_uniq_id
subject.get_uniq_id
end
it { should get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
end
Or, to bind the output to subject
:
require 'spec_helper'
describe IdGeneration do
class Dummy
include IdGeneration::ClassMethods
end
let(:dummy) { Dummy.new }
subject { dummy }
describe "#get_uniq_id" do
subject { dummy.get_uniq_id }
it { should match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/) }
end
end
来源:https://stackoverflow.com/questions/29368762/implicit-using-subject-in-rspec-example-doesnt-work