Rspec,在Rails应用程序控制器中存在对象的存在

时间:2014-12-11 16:01:30

标签: ruby-on-rails ruby rspec

我的应用程序控制器中有一个方法'get_location_details',在每次操作之前找到场地后调用。它看起来像这样,

  def get_venue 
    @venue = Venue.friendly.find(params[:venue_id])
  end 

  def get_location_details
    @venue_information = {
    opening_times: @venue.facility_with_opening_hours.any? ? venue.facility_with_opening_hours.first.opening_times_for_week(Date.today) : '',
    location:   {address1:   venue.address1, 
                 address2:   venue.address2, 
                 town:       venue.town, 
                 county:     venue.county, 
                 postcode:   venue.postcode},
    contact:    {email:      venue.email, 
                 telephone:  venue.telephone},
    social:     {facebook:   venue.facebook,
                 twitter:    venue.twitter}    
    }
  end

我想开始测试我。输出,ii。上下文(即场地不存在的地方)。 我认为为了达到这个目的,我需要留下场地的存在,这是我似乎无法弄清楚该怎么做。

  describe "get_location_details" do 
    before do 
      test_hash = [{:day=>"Mon - Fri", :open=>"2001-01-01 06:30:00 +0000", :close=>"2001-01-01 22:00:00 +0000", :closed=>false},
                  {:day=>"Sat", :open=>"2001-01-01 08:00:00 +0000", :close=>"2001-01-01 19:00:00 +0000", :closed=>false},
                  {:day=>"Sun", :open=>"2001-01-01 08:00:00 +0000", :close=>"2001-01-01 17:00:00 +0000", :closed=>false}]
      allow(controller).to receive(:venue).and_return(venue)
      allow(venue).to receive(:facility_with_opening_hours).and_return(test_hash)
    end

    it "returns http success" do
      expect(controller.send(:get_location_details).is_a?(Hash)).to be_truthy
    end

  end 

但是我的测试仍然失败

   undefined method `facility_with_opening_hours' for nil:NilClass

表示场地没有被扣留。我怎么能把场地留下来?我在这做错了什么? 我经常在应用程序控制器测试中绊倒,但我想要掌握它。如果有人可以推荐任何进一步的阅读,将不胜感激。

非常感谢

1 个答案:

答案 0 :(得分:1)

我不确定您是否可以轻松地在rspec中存根成员。您可以使用值设置成员,或者(最好)重构代码以从getter而不是成员中读取值:

def venue 
  @venue ||= Venue.friendly.find(params[:venue_id])
end 

def location_details
  @venue_information ||= {
    opening_times: venue.facility_with_opening_hours.any? ? venue.facility_with_opening_hours.first.opening_times_for_week(Date.today) : '',
    location:   {address1:   venue.address1, 
    address2:   venue.address2, 
    town:       venue.town, 
    county:     venue.county, 
    postcode:   venue.postcode},
    contact:    {email:      venue.email, 
             telephone:  venue.telephone},
    social:     {facebook:   venue.facebook,
             twitter:    venue.twitter}    
  }
end