RSPEC访问application_controller方法,例如'current_user'
-
03-10-2019 - |
题
我正在尝试使用RSPEC将方法(使用修改后的RESTFUL_AUTHENTICATION AUTH解决方案)固执。我完全不确定如何在控制器规格中访问此方法。 current_user本身不起作用。我需要先获得控制器本身吗?我该怎么做呢?
使用 rails 2.3.5
, rspec 1.3.0
和 rspec-rails 1.3.2
# my_controller_spec.rb
require 'spec_helper'
describe MyController do
let(:foos){ # some array of foos }
it "fetches foos of current user" do
current_user.should_receive(:foos).and_return(foos)
get :show
end
end
生产
NoMethodError in 'ChallengesController fetches foos of current user'
undefined method `current_user' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1::Subclass_1::Subclass_2::Subclass_2:0x7194b2f4>
解决方案
RSPEC轨道给您一个 controller
在控制器示例中使用的方法。所以:
controller.stub!(:current_user).with(:foos).and_return(foos)
应该工作。
其他提示
怎么知道在哪里找到 current_user
?这应该解决:
subject.current_user.should_receive(:foos).and_return(foos)
我对Restful_authentication并不完全熟悉,只是Authlogic and Steans,但这可能是相似的 current_user
是一种控制器方法,而不是对象,这就是为什么调用 should_receive
它无法正常工作(您正在对物体设定期望 current_user
返回, ,但是在期望范围内无法访问该方法)。
试试这个:
stub!(:current_user).and_return(foos)
我读了这本书,对我的调整了一点。如果您只想将用户对象传递到RSPEC测试中,则可以使用以下方式:
首先,在RSPEC测试中创建一个用户对象。例如:(使用您需要或需要创建用户对象的任何属性。)
user = user.create(名称:“ ted”)
(注意:您也可以使用FactoryGirl的工厂。)
现在,使用该用户对象保存到变量“用户”中,请在同一RSPEC测试中执行此操作:
controller.stub!(:current_user).and_return(用户)
那应该起作用...