为什么在Rails 5的测试中无法传递参数?

时间:2019-03-22 04:33:46

标签: rest ruby-on-rails-5

我在users_controller.rb中有以下代码:

def create
  params = user_params
  x = 1

  render :json => { :message => "New user created!"}, :status => :ok
end

private

def user_params
  params.permit!
end

它现在显然没什么用。我之前没有过滤器。

我还有以下测试代码:

RSpec.describe UsersController, type: :controller do
fixtures :users, :clients
include AuthHelper

before do
  @request.headers["Content-Type"] = 'application/json'
  @request.headers["Accept"] = 'application/json'

  @default_registered_users = 3
end

describe '#create' do
  context 'a user with a valid authorization token' do
    before do
      init_headers_for_admin
    end

    context 'with a valid set of input parameters' do
      before do
        @new_user = {
          :username => 'blorp',
          :email => 'blorp@blorpville.com',
          :role => 'user',
          :name => 'Blorp Blorperson'
        }.as_json
      end

      it 'should create a new user' do
        post :create, params: @new_user

        expect(response).to have_http_status(:ok)
      end
    end
  end

spec_helper.rb内,我具有以下帮助函数:

  def init_headers_for_admin
    # Manually added to the database, this username/password is good.
    init_headers_with_login 'scottj', '771625142'
  end

  def init_headers_with_login (username, password)
    auth_token = login username, password
    init_headers_with_auth_token auth_token
  end

  def login (username, password)
    unless @request
      return login_for_integration_tests username, password
    end

    old_controller = @controller
    @controller = UsersController.new

    get_headers_for_login(username, password).each { |key, value|
      @request.headers[key] = value
    }

    post :login

    response_body = JSON.parse response.body

    @controller = old_controller
    response_body['auth_token']
  end

  def login_for_integration_tests(username, password)
    headers = get_headers_for_login username, password

    post '/login', headers: headers

    response_body = JSON.parse response.body
    response_body['auth_token']
  end

  def get_headers_for_login(username, password)
    combined_login_password = username + ":" + password
    encoded_username_password =. Base64.encode64(combined_login_password)

    headers = get_default_headers
    headers['X-Api-Key'] = Client.find_by_id(1234).api_key
    headers['Authorization'] = 'Basic ' + encoded_username_password

    headers
  end

运行测试并在设置x=1的代码处设置断点时,我得到params变量的以下值:{"controller"=>"users", "action"=>"create", "user"=><ActionController::Parameters {} permitted: true>}

请注意,usernamenameemailrole的出现是如何不存在的,但是一个神秘的哈希称为user 当前,但未填充。

我看到的问题是,无论我做什么,我似乎都无法使users_controller实际传递任何参数。我以为,起初,不允许使用正确的参数是一个问题,因此我在params.permit!中执行的users_controller是一个问题。不过,这似乎无法解决问题。

有人可以告诉我我在做什么错吗?我一直在想办法解决这个问题。

0 个答案:

没有答案