2015-04-23 73 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