【问题标题】:Rails - Testing ApplicationController with rspecRails - 使用 rspec 测试 ApplicationController
【发布时间】:2012-09-26 05:08:48
【问题描述】:

我想将常用的控制器动作、索引、显示、创建等放在 ApplicationController 中,如下所示:

class ApplicationController < ActionController::Base
  respond_to :json

  def index
    #implementation
  end

  def show
   #implementation
  end

  def update
    #implementation
  end
end

应用只会返回 JSON。

我编写了以下规范以使用 RSPEC 的匿名控制器对此进行测试

describe ApplicationController do
  controller do ; end

  describe 'Get :index' do
    it 'should respond to index' do
      get :index

      response.code.should eq "200"
    end
  end
end

上述规范给出以下错误:

ActionView::MissingTemplate:缺少模板匿名/索引, 应用程序/索引与 {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder]}。搜索:* “#”

任何人都可以提出一种使用匿名控制器进行这项工作的方法吗?

【问题讨论】:

  • 使用xhr :get :index 代替get :index 有帮助吗?

标签: ruby-on-rails rspec


【解决方案1】:

试试这个可能会有帮助

你的控制器喜欢

def index
end

你的 rspec 测试像

describe "GET index" do
  it "should respond to index" do
    get :index
    response.code.should eq "200"
  end
end

在您的应用程序/文件夹中创建 index.html.erb

然后测试它。

【讨论】:

  • 在 index 动作中写入 render :nothing => true 然后测试。
  • 索引操作会返回一些东西。你的意思是在规范中覆盖它吗?这将不会测试任何内容。
【解决方案2】:

描述“获取索引”做

it "returns correct JSON" do
  # @groups.should have(2).items
  get :index, :format => :json
  response.should be_success
  body = JSON.parse(response.body)
  body.should include('group')
  groups = body['group']
  groups.should have(2).items
  groups.all? {|group| group.key?('customers_count')}.should be_true
  groups.any? {|group| group.key?('customer_ids')}.should be_false
end

结束

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多