ruby-on-rails - 未调用 RSpec Controller 测试失败方法

标签 ruby-on-rails testing rspec

我正在尝试为“UsersController”编写一个简单的 RSpec 测试来测试索引方法。

Controller 索引方法的代码如下所示:

# GET /users
# GET /users.json
def index
  @users = User.all
  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @users }
  end
end

我正在尝试测试是否调用了“all”方法以及是否呈现了索引 View 。这是我的 Rspec 代码:

require 'spec_helper'

describe UsersController do
    describe 'get index', :type => :controller do
        before :each do
          @fake_users = [double('user1'), double('user2')]
        end
        it 'should call the model method that retrieves all Users' do
          User.should_receive(:all).once.and_return(@fake_users)
          get :index
        end
        describe 'after valid search' do
          before :each do
        User.stub(:all).and_return(@fake_users)
        get :index
          end
          it 'should select the index template for rendering' do
        response.should render_template('index')
          end
          it 'should make the users results available to that template' do
        assigns(:users).should == @fake_users
          end
        end
    end
end

但是,这会导致“获取索引”测试失败,并显示以下消息:

Failure/Error: User.should_receive(:all).once.and_return(@fake_users)
       (<User(id: integer, firstname: string, lastname: string, username: string, email: string, password_digest: string, created_at: datetime, updated_at: datetime) (class)>).all(any args)
           expected: 1 time with any arguments
           received: 0 times with any arguments
     # ./spec/controllers/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

任何人都可以阐明我做错了什么吗?

最佳答案

问题是由 UsersController 要求先登录引起的。所以 Controller 看起来像:

class UsersController < AuthenticatedController

因此 RSpec 无法访问该路径。

关于ruby-on-rails - 未调用 RSpec Controller 测试失败方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465111/

相关文章:

ruby - RSpec 模拟对象示例

ruby-on-rails - 使用橡胶将 Rails 应用程序部署到 AWS - 无 :NilClass error

ruby-on-rails - 将哈希深度转换为平面路径数组

mysql - Rails更新数据库方法

testing - 在 JMeter 中看到我的应用程序压力测试后令人震惊的结果

ruby-on-rails - 如果快速规范通过,如何让守卫只运行慢速规范

ruby - 如何使用 rest-client 资源检查响应代码

jquery - Rails 博客文件按日期搜索

testing - 需要解释如何计算测试自动化的投资返回

javascript - 如何测试具有关系依赖性的 Ember 模型的计算属性?