Rspec - 如何为类方法编写测试

时间:2015-04-23 09:27:29

标签: ruby-on-rails ruby rspec

成为RoR和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

到目前为止这是正确的吗?然而,测试似乎没有返回任何方法?

1 个答案:

答案 0 :(得分: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)只是"注册"要调用的方法(在您的示例中,它填充数据库),但不会自动执行。只要您不需要从此方法返回的值,您应该坚持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

希望有所帮助。

祝你好运!

<强>更新

如何通过多次出现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