【问题标题】:How to write rspec for index action of api controllers如何为 api 控制器的索引操作编写 rspec
【发布时间】:2013-09-23 07:49:59
【问题描述】:

当我运行这个规范时,它总是给出 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

【问题讨论】:

  • 您遇到的错误是什么?它引用了哪一行?
  • 运行规范后,预期有歌曲实例,但得到了零。所以基本上它没有通过测试。基本匹配器测试。

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


【解决方案1】:

你的控制器应该有实例变量。所以改变

 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

应该这样做:)

【讨论】:

    猜你喜欢
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    相关资源
    最近更新 更多