【发布时间】:2017-11-14 18:22:04
【问题描述】:
以下是我尝试使用 RSpec 测试的控制器方法
def login
authorized_user = authenticate(params[:email], params[:password])
if authorized_user
# Creating a session if the User is Authorized
session[:user_email] = authorized_user
redirect_to(controller: 'home', action: 'details')
else
flash[:invalid] = 'Invalid Username or Password'
redirect_to(action: 'signin')
end
end
def authenticate(email = '', password = '')
url = 'http://localhost:8080/getUser/' + email
response = RestClient.get(url)
resp = JSON.parse(response)
if resp[0]['id'] == 0
return false # If no user exists return false
else
return resp[0]['email']
end
end
在这里,我试图模拟 RestClient.get() 方法并向登录方法返回一个虚拟电子邮件以设置会话。 以下是我的规范文件
it "mocks the api method checks the user with a Invalid email" do
RestClient.should_receive(:get).and_return('[{"id":"0"}]')
get :authenticate
expect(response).to redirect_to '/signin'
end
但在这里我需要将电子邮件和密码传递给身份验证方法。我在这里面临两个问题 1)如何将电子邮件和密码传递给身份验证方法 2) 当我在没有上述参数的情况下调用 authenticate 方法时,会出现这样的错误
Failure/Error: url = 'http://localhost:8080/getUser/' + email
TypeError:
no implicit conversion of nil into String
那么我如何模拟 RestClient.get() 方法并通过使用一些虚拟电子邮件和密码调用 authenticate 方法返回一些 JSON 作为响应?
【问题讨论】:
-
get :authenticate('abc@gmail.com', '1234567890')你可以像这样传递电子邮件和密码。 -
@Gabbar 我得到这个错误语法错误,意外'(',期待keyword_end get :authenticate('ssksmk@gmail','ss')
标签: ruby-on-rails ruby rspec rspec-rails