2013-11-27 99 views
1

我使用Rspec來測試我的Rails應用程序。在我的Model目錄中,我有一個名爲location_services.rb的Ruby文件。在這個文件中是在Rails應用程序中測試PORO

module LocationServices 
    class IpLocator 
    attr_reader :response, :status 
    def initialize(response, status) 
     .... 
    end 
end 

我該如何測試一個IpLocator對象本身的創建?我只想調用IpLocator.create_type_1.response並測試我在沒有整個rails堆棧的情況下得到的結果。

create_type_1是IpLocator上的一個類方法,它將調用new來實例化一個對象。

+1

需要更多信息。你究竟想要測試什麼?該對象是在執行其他操作時創建的?更廣泛的背景將會有所幫助。 –

回答

2

我假設你的文件看起來更像是這樣的:

module LocationServices 
    class IpLocator 
    attr_reader :response, :status 
    def initialize(response, status) 
     .... 
    end 

    def self.create_type_1 
     self.new 
     # Possibly some more code here 
    end 
    end 
end 

您可以創建spec/models/location_services_spec.rb並整理其結構是這樣的:

require 'spec_helper' 

describe LocationServices::IpLocator do 
    describe '.create_type_1' do 
    locator = LocationServices::IpLocator.create_type_1 
    expect(locator).to # finish your assertion here 
    end 
end 

的命名約定可能工作會不正常。如果RSpec找不到所需的類,則可以嘗試移動並將其重命名爲location_services.rbapp/models/location_services/ip_locator.rb。如果你這樣做,移動並重命名爲spec/models/location_services/ip_locator_spec.rb。但是,要求spec_helper.rb文件可能會爲您的測試加載Rails堆棧。這可能取決於你的文件如何設置。

+0

看起來不錯,會嘗試所有這一切。 – slindsey3000

相關問題