我正在尝试为“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/