2012-03-14 55 views
2

试图为我已经编写的代码编写一些测试,以期使用测试驱动开发来扩展我的代码。Rspec - 访问巫术方法/变量

我有一个控制器,其索引操作调用一个'user_info'方法,该方法仅依靠Sorcery的current_user变量收集一些实例变量。例如:

def user_info 
    @current_A = current_user.a 
    @current_B = current_user.b 
end 

def index 
    user_info 
    // rest of the method goes here 
end 

我开始使用rspec编写一些测试,只是为了感受测试这个代码库。我的控制器规范是非常基本的,看起来像这样:

describe MyController do 
    describe "GET 'index'" do 
    get 'index' 
    response.should be_success 
    end 
end 

不过,我得到以下错误,当我尝试运行此规格: NoMethodError:未定义的方法“一个”假:FalseClass

第一所有,我怎么让我的规格识别Sorcery方法current_user?出于好奇,为什么current_user被标记为FalseClass的实例?如果它没有调用Sorcery方法(并且我没有在我的代码中的任何其他地方定义current_user),它应该不显示为零吗?

+0

总是最好接受最好的答案,或者你自己回答,并接受。由于 – 2014-08-12 00:28:29

回答

0

Richard,问题很可能是您没有current_user。

要做到这一点,您需要模拟登录过程。

你可以用控制器规格来做到这一点,但我没有一个很好的例子。我正在编写有关现有代码的规范,就像你一样,而且使用请求规范是有道理的。

我也没有一个巫术(我应该!!),我在这里使用水豚填写表格。不过,这里是我的规格是什么样子:

(这里:账户是一样的:用户会)

所以工厂另当别论了,我的这个样子

context "when logged in" do 

before :each do 
@account = Factory.create(:account) 
@current_game = Factory(:game_stat) 
visit login_path 
    fill_in 'Username or Email Address', :with => @account.email 
    fill_in 'Password', :with => @account.password 
    click_button('Log in') 

末:

Factory.define :account do |f| 
f.sequence(:username) { |n| "ecj#{n}" } 
f.sequence(:email) { |n| "ecj#{n}@edjones.com" } 
f.password "secret" 
f.password_confirmation {|u| u.password } 

您不必使用的工厂,但是你需要得到该会话和current_user建立。

3

要使用巫术测试助手,您需要在spec_helper.rb中的以下行。

以下需求是在Rspec.configure块:

RSpec.configure do |config| 
    config.include Sorcery::TestHelpers::Rails 
end 

你在的地方之后,你可以使用巫术测试助手。对于Controller测试,您可以将以下内容添加到您的测试中。

@user = either a fixture or a factory to define the user 
login_user 

如果您不想指定@user您可以传递参数。

login_user(fixture or factory definition) 

一旦您登录current_user应该可用于您的测试。

logout_user也可用。

请参阅Sorcery Wiki了解有关设置用户夹具以与login_user帮助程序配合使用的信息。

+0

采取@nmott建议增加法术帮手,这是我的用途控制器规格的最高工作rpsec配置后 - 让(:用户){ U = FactoryGirl.create(:用户)\ n login_user(U)\ n u } – Alex 2014-01-07 06:42:59

0

在重要的一点是要确保,如果你正在使用的创建后,用户被激活:巫术user_activation子模块。

所以,如果你使用的制造宝石,那会是什么样子,

Fabricator(:properly_activated_user, :from => :user) do 
    after_create { |user| user.activate! } 
end 
0

正如@nmott提到你需要做两件事情:使用

1)注册文本辅助方法:

RSpec.configure do |config| 
    config.include Sorcery::TestHelpers::Rails 
end 

2)在你的榜样访问current_user通过controller.current_user这样的:

login_user(user) 
expect(controller.current_user).to be_present