2015-04-23 75 views
0

RoR和Rspec是新手我很努力爲這種情況編寫測試。Rspec - 如何編寫類方法的測試

# Table name: countries 
# 
# id    :integer   not null, primary key 
# code   :string(255)  not null 
# name   :string(255) 
# display_order :integer 
# create_user_id :integer   not null 
# update_user_id :integer 
# created_at  :datetime   not null 
# updated_at  :datetime 
# eff_date  :date 
# exp_Date  :date 

我想測試在全國模型這種方法:

def self.get_default_country_name_order 
     countries = Country.in_effect.all.where("id !=?" ,WBConstants::DEFAULT_COUNTRY_ID).order("name") 
    result = countries 
    end 

在我country_spec我有這樣的:

describe Country do 
    before(:all) do 
    DatabaseCleaner.clean_with(:truncation) 
    end 
    let(:user){create(:user)} 
    let(:country3){create(:country,code:"AUS", name:"Australia", create_user:user, eff_date: Time.new(9999,12,31), exp_date: Time.new(9999,12,31))} 

    after(:all) do 
    DatabaseCleaner.clean_with(:truncation) 
    end 

這個國家會過期,一個有一個名爲範圍在過濾掉過期國家的模型上。我的測試應該是這樣的:

it "should not include an expired country" do 
    c = Country.get_default_country_name_order 
    end 

這到目前爲止是否正確?該測試似乎沒有從該方法返回任何內容?

回答

0

是的,這是正確的方向。

若要堅持您的Country模型解決的問題,您應該改變這樣的:

let(:country3){create(:country,code:"AUS", name:"Australia", create_user:user, eff_date: Time.new(9999,12,31), exp_date: Time.new(9999,12,31))} 

這樣:

before {create(:country,code:"AUS", name:"Australia", create_user:user, eff_date: Time.new(9999,12,31), exp_date: Time.new(9999,12,31))} 

或在您的測試呼叫:country3

it "should not include an expired country" do 
    country3 
    c = Country.get_default_country_name_order 
end 

let(:country3)只是「註冊」一個被調用的方法(in你的例子,它填充數據庫),但它不會自動執行。只要你不需要從這個方法返回的值,你應該堅持before,它會自動執行代碼。

另一方面,您可能需要測試Country型號的返回值。例如:

it "should not include an expired country" do 
    example_country = country3 
    c = Country.get_default_country_name_order 
    expect(c).to eq example_country 
end 

希望有所幫助。

祝你好運!

UPDATE

如何與before

describe Country do 
    before(:all) do 
    DatabaseCleaner.clean_with(:truncation) 
    end 
    let(:user){create(:user)} 
    let(:country3){create(:country,code:"AUS", name:"Australia", create_user:user, eff_date: Time.new(9999,12,31), exp_date: Time.new(9999,12,31))} 

    after(:all) do 
    DatabaseCleaner.clean_with(:truncation) 
    end 

    describe "#get_default_country_name_order" do 
    # you can register another "before" 
    before {create(:country,code:"AUS", name:"Australia", create_user:user, eff_date: Time.new(9999,12,31), exp_date: Time.new(9999,12,31))} 

    # or simpler - this will call your method 
    # before "it", and create the record 
    # before { country3 } 

    it "should not include an expired country" do 
     # your expectations here 
    end 
    end 
+0

多次出現結構規範例子中,我更新了我的OP,以顯示如何描述和之前做。這是否會影響你的答案? – user3437721

+0

嘿@ user3437721,包含的代碼並沒有真正改變太多,你可能會在你的規範中出現多次'before'。請查看更新後的答案,瞭解如何構建您的規格示例 –

+0

偉大的幫助,讓它工作正常!謝謝 – user3437721