2015-03-31 60 views
0

我要測試模型問題get_uniq_id方法。在rspec示例中隱含使用主題不起作用

應用程序/模型/顧慮/ 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> 

如果我指定s明確指出it { should subject.get_uniq_id.match(/[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{2}-[A-Z]{2}/)}。有用。

我是否需要明確指定主題?

回答

0

你調用方法的方式 - 是的。該方法需要在對象上調用。在這種情況下,get_uniq_id將在當前正在運行的測試環境中執行,這就是彈出錯誤的原因。

您可以使用快捷鍵可能是這樣:

it { should respond_to :get_uniq_id } 

將執行類似subject.respond_to?(:get_uniq_id)測試。該方法調用,但是,需要明確的接收器。

您可以更新您的測試,以使用它作爲你的榜樣,如果你修改它稍微:

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