我目前正在使用RSpec来测试我的Rails 4应用程序,在测试时,我发现了这个奇怪的问题:subject.current_user在上下文中的第二个方法中为nil。代码段:
describe 'GET #register_as_team:' do
context 'user logged in but not admin:' do
login_user
it 'should redirect_to user_path if user is not student' do
get :register_as_team, id: subject.current_user.id
expect(response).to redirect_to(user_path(subject.current_user))
expect(flash[:danger]).not_to be_nil
end
it 'should redirect_to student_path if user is a non-pending student' do
student = FactoryGirl.create(:student, user: subject.current_user, is_pending: false)
get :register_as_team, id: subject.current_user.id
expect(response).to redirect_to(student_path(student))
end
end
end
因此,当第一次使用subject.current_user
时,它就可以了,我可以获取已记录的用户,但在第二种方法中它返回nil。
有关背景信息,login_user
是这样的:
module ControllerMacros
def login_user(user = nil)
before(:each) do
# @request.env["devise.mapping"] = Devise.mappings[:user]
user ||= User.find_by(email: 'default_user@controller.spec')
user ||= FactoryGirl.create(:user, email: 'default_user@controller.spec', uid: 'default_user.controller.spec')
sign_in user
end
end
end
答案 0 :(得分:0)
在示例中,subject
只能是resolved once
当您执行get :register_as_team, id: subject.current_user.id
时,您基本上已经解决了subject
并且subject.current_user
未在下一行得到解决。
试试这个:
describe 'GET #register_as_team:' do
context 'user logged in but not admin:' do
login_user
it 'should redirect_to user_path if user is not student' do
user = subject.current_user
get :register_as_team, id: user.id
expect(response).to redirect_to(user_path(user))
expect(flash[:danger]).not_to be_nil
end
it 'should redirect_to student_path if user is a non-pending student' do
student = FactoryGirl.create(:student, user: subject.current_user, is_pending: false)
user = subject.current_user
get :register_as_team, id: user.id
expect(response).to redirect_to(student_path(student))
end
end