尝试为我已经编写的代码编写一些测试,以期使用测试驱动开发来扩展我的代码。
我有一个控制器,它的索引操作调用了一个'user_info‘方法,这个方法只是收集了一些依赖于巫师的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: undefined method 'a‘for false:FalseClass
首先,我如何让我的规范识别魔法方法current_user?出于好奇,为什么current_user被标记为FalseClass的一个实例?如果它没有调用Sorcery方法(并且我在代码中没有在其他地方定义current_user ),它是否应该显示为nil?
发布于 2012-03-30 20:08:07
要使用魔法测试助手,您需要在spec_helper.rb中使用以下代码行。
Rspec.configure块中需要包含以下内容:
RSpec.configure do |config|
config.include Sorcery::TestHelpers::Rails
end准备好之后,你就可以使用魔法测试助手了。对于控制器测试,您需要将以下内容添加到测试中。
@user = either a fixture or a factory to define the user
login_user如果你不想指定@user,你可以传递一个参数。
login_user(fixture or factory definition)登录后,您的测试应该可以使用current_user。
logout_user也是可用的。
有关设置用户装置以使用login_user辅助对象的信息,请参见Sorcery Wiki。
发布于 2012-03-14 21:29:45
理查德,问题很可能是你没有current_user。
为此,您需要模拟登录过程。
您可以使用控制器规范来做到这一点,但我在这里没有一个很好的示例。我是在现有代码上编写规范的,就像您一样,使用请求规范来代替它是有意义的。
我也没有为巫师准备的(我应该!)我在这里使用Capybara来填写表单。尽管如此,下面是我的规范的样子:
(此处:帐户与:用户将相同)
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。
发布于 2013-05-18 08:44:29
重要的一点是确保用户在创建后被激活,如果你使用的是魔法的:user_activation子模块。
所以,如果你使用的是人造宝石,它看起来就像,
Fabricator(:properly_activated_user, :from => :user) do
after_create { |user| user.activate! }
endhttps://stackoverflow.com/questions/9701914
复制相似问题