在 rspec 示例中隐式使用主题不起作用 [英] Implicit using subject in rspec example doesn't work
问题描述
我将测试模型关注 get_uniq_id 方法.
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
规范/关注点/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
它抛出了错误:
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>
如果我明确指定主题它{应该subject.get_uniq_id.match(/[AZ]{2}-[0-9]{2}-[AZ]{2}-[0-9]{2}-[AZ]{2}/)
}.它有效.
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?
推荐答案
您调用方法的方式 - 是的.该方法需要在对象上调用.在这种情况下,get_uniq_id
将在当前运行的测试上下文中执行,这就是为什么会弹出错误.
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 }
哪个将执行类似于 subject.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
或者,将输出绑定到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
这篇关于在 rspec 示例中隐式使用主题不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!