【问题标题】:How to test json format with specific url use RSpec Rails 4.0?如何使用 RSpec Rails 4.0 测试具有特定 url 的 json 格式?
【发布时间】:2020-05-24 01:26:03
【问题描述】:

我需要测试像 "/users.json?search=" + "[params]" 之类的 url:

it "renders a successful response" do
 get :show, params: "/users.json?search=c"
 expect(response).to have_http_status(200)
 expect(response).to be_successful
end

我的控制器喜欢

def index
  @users = User.search(params[:search]).limit(10)

  respond_to do |f|
    f.json { render json: @users }
  end
end

当我运行测试时出现这个错误:

Failure/Error: before { get :show, params: "/users.json?search=unk" }

NoMethodError:
undefined method `symbolize_keys' for "/users.json?search=unk":String
```

【问题讨论】:

    标签: ruby-on-rails json testing rspec rspec-rails


    【解决方案1】:

    在 Rails 4 中,您传递参数而不定义 params 键:

    get :show, format: :json, search: c
    

    从 Rails 5 开始,您可以使用 params 键传递参数:

    get :show, format: :json, params: { search: c }
    

    【讨论】:

      猜你喜欢
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多