Rails模型类方法的RSpec测试

时间:2015-09-09 08:04:49

标签: ruby-on-rails rspec

我的模型中有一个方法

class Announcement < ActiveRecord::Base
  def self.get_announcements
    @announcements = Announcement.where("starts <= :start_date and ends >= :end_date and disabled = false",
      {:start_date => "#{Date.today}", :end_date => "#{Date.today}"})
    return @announcements 
  end
end

我正在尝试为此方法编写rspec,因为我是rspec的新手,不能继续

describe ".get_announcements" do
  before { @result = FactoryGirl.create(:announcement) }
  it "return announcements" do 

  end
end

请帮忙

2 个答案:

答案 0 :(得分:1)

解决我的问题

describe ".get_announcements" do
    before { @result = FactoryGirl.create(:announcement) }
    it "return announcement" do
      Announcement.get_announcements.should_not be_empty
    end
  end

答案 1 :(得分:0)

describe ".get_announcements" do
  let!(:announcements) { [FactoryGirl.create!(:announcement)] }
  it "returns announcements" do
    expect(Announcement.get_announcements).to eq announcements
  end
end

请注意let!使用announcements立即(不是懒惰)分配给class Announcement < ActiveRecord::Base def self.get_announcements Announcement.where("starts <= :start_date and ends >= :end_date and disabled = false", {:start_date => "#{Date.today}", :end_date => "#{Date.today}"}) end end

类方法真的需要定义实例变量吗?如果没有,可以重构为:

$.Deferred