简体   繁体   English

使用RSpec测试时如何将参数传递给控制器​​方法

[英]How to pass argument to a controller method while testing with RSpec

Below are my controller methods which I am trying to test with RSpec 以下是我尝试使用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

Here I am trying to mock the RestClient.get() method and return a dummy email to the login method to set the session with. 在这里,我尝试模拟RestClient.get()方法,并向登录方法返回虚拟电子邮件以设置会话。 Below is my spec file 以下是我的规格文件

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

But here I need to pass email and password to the authenticate method. 但是在这里,我需要将电子邮件和密码传递给authenticate方法。 I am facing two problems here 1) How to pass the email and password to the authenticate method 2) When I call the authenticate method without the arguments like above I get an error like this 我在这里面临两个问题1)如何将电子邮件和密码传递给authenticate方法2)当我在没有上述参数的情况下调用authenticate方法时,会收到这样的错误

Failure/Error: url = 'http://localhost:8080/getUser/' + email

     TypeError:
       no implicit conversion of nil into String

So how can I mock the the RestClient.get() method and return some JSON as response by calling the authenticate method with some dummy email and password? 那么,我该如何模拟RestClient.get()方法并通过使用一些虚拟电子邮件和密码调用authenticate方法来返回一些JSON作为响应?

在RSpec中,您可以在get方法中将参数作为Hash传递

get :show, email: 'abc@gmail.com', password: '1234567890'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM