如何为api控制器的索引动作编写rspec

时间:2013-09-23 07:50:00

标签: ruby-on-rails ruby-on-rails-3 rspec ruby-on-rails-3.2

当我运行此规范时,它总是给出nil对象,任何人都可以帮助我。

 require 'spec_helper'

   describe Api::SongsController do
    describe "GET index" do
     it "assigns songs json" do
      song = Song.create(:title => "song")
      get :index, :format => :js
      assigns(:songs).should eq([song])
      end
     end        
   end

我的控制器代码

     def index
      songs = Song.all
      if !songs.empty?
       respond_with songs
      else
       render :json => {:message => "No songs found."}
      end
     end

1 个答案:

答案 0 :(得分:0)

您的控制器应具有实例变量。所以改变

 def index
  songs = Song.all
  if !songs.empty?
   respond_with songs
  else
   render :json => {:message => "No songs found."}
  end
 end

 def index
  @songs = Song.all
  if !@songs.empty?
   respond_with @songs
  else
   render :json => {:message => "No songs found."}
  end
 end

应该这样做:)