Ruby on Rails - ошибка NilClass по GET-запросу Фарадея
Использование Rails 5.1.4, Ruby 2.4
Я пытаюсь подключиться к API, используя Фарадей, что я делал раньше без проблем, но я получаю следующую ошибку при запуске RSpec:
SearchController GET #index возвращает http успех. Ошибка / Ошибка: response = @conn.get("/congress/v1/members/house/#{state}/current.json")
NoMethodError:
undefined method `get' for nil:NilClass
Did you mean? gem
# ./app/controllers/search_controller.rb:9:in `block in index'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/faraday-0.13.1/lib/faraday/connection.rb:88:in `initialize'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/faraday-0.13.1/lib/faraday.rb:67:in `new'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/faraday-0.13.1/lib/faraday.rb:67:in `new'
# ./app/controllers/search_controller.rb:5:in `index'
# ./spec/controllers/search_controller_spec.rb:7:in `block (3 levels) in <top (required)>'
2) пользователь может искать членов дома. Пользователь отправляет действительное имя состояния. Ошибка / Ошибка: response = @conn.get("/congress/v1/members/house/#{state}/current.json")
NoMethodError:
undefined method `get' for nil:NilClass
Did you mean? gem
# ./app/controllers/search_controller.rb:9:in `block in index'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/faraday-0.13.1/lib/faraday/connection.rb:88:in `initialize'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/faraday-0.13.1/lib/faraday.rb:67:in `new'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/faraday-0.13.1/lib/faraday.rb:67:in `new'
# ./app/controllers/search_controller.rb:5:in `index'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/etag.rb:25:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/conditional_get.rb:25:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/head.rb:12:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/session/abstract/id.rb:232:in `context'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/session/abstract/id.rb:226:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/railties-5.1.4/lib/rails/rack/logger.rb:36:in `call_app'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/railties-5.1.4/lib/rails/rack/logger.rb:24:in `block in call'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/railties-5.1.4/lib/rails/rack/logger.rb:24:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/method_override.rb:22:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/runtime.rb:22:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/sendfile.rb:111:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/railties-5.1.4/lib/rails/engine.rb:522:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/urlmap.rb:68:in `block in call'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/urlmap.rb:53:in `each'
# /Users/user/.rvm/gems/ruby-2.4.0@global/gems/rack-2.0.3/lib/rack/urlmap.rb:53:in `call'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/rack-test-0.7.0/lib/rack/mock_session.rb:30:in `request'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/rack-test-0.7.0/lib/rack/test.rb:249:in `process_request'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/rack-test-0.7.0/lib/rack/test.rb:59:in `get'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/rack_test/browser.rb:69:in `process'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/rack_test/browser.rb:41:in `process_and_follow_redirects'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/rack_test/browser.rb:32:in `submit'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/rack_test/form.rb:78:in `submit'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/rack_test/node.rb:64:in `click'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/node/element.rb:143:in `block in click'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/node/base.rb:85:in `synchronize'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/node/element.rb:143:in `click'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/node/actions.rb:25:in `click_link_or_button'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/session.rb:776:in `block (2 levels) in <class:Session>'
# /Users/user/.rvm/gems/ruby-2.4.0/gems/capybara-2.15.1/lib/capybara/dsl.rb:50:in `block (2 levels) in <module:DSL>'
# ./spec/features/user_can_search_by_state_spec.rb:11:in `block (2 levels) in <top (required)>'
Вот мой контроллер поиска, где находится логика, пока я не смогу исправить эту ошибку и извлечь ее в другом месте:
class SearchController < ApplicationController
def index
state = params[:state]
@conn = Faraday.new(url: "https://api.propublica.org") do |faraday|
faraday.headers["X-API-KEY"] = "<$MY-API-KEY>"
faraday.adapter Faraday.default_adapter
response = @conn.get("/congress/v1/members/house/#{state}/current.json")
results = JSON.parse(response.body, symbolize_names: true)[:results]
@members = results.map do |result|
Member.new(result)
end
end
end
end
И чтобы быть тщательным, вот моя модель члена:
class Member
attr_reader :name,
:role,
:party,
:district,
:seniority
def initialize(attributes = {})
@name = attributes[:name]
@role = attributes[:role]
@party = attributes[:party]
@district = attributes[:district]
@seniority = attributes[:seniority]
end
end
1 ответ
@conn
не определяется должным образом, поэтому, когда он пытается вызвать @conn.get
это действительно зовет nil.get
который поднимает undefined method get for nil
, Убедитесь, что вы определили @conn
прежде чем пытаться ссылаться на него. Я очистил ваш пример, чтобы показать проблему:
class SearchController < ApplicationController
def index
state = params[:state]
@conn = Faraday.new(url: "https://api.propublica.org") do |faraday|
faraday.headers["X-API-KEY"] = "<$MY-API-KEY>"
faraday.adapter Faraday.default_adapter
# you are trying to reference @conn here
response = @conn.get("/congress/v1/members/house/#{state}/current.json")
results = JSON.parse(response.body, symbolize_names: true)[:results]
@members = results.map do |result|
Member.new(result)
end
end # but @conn is not defined until you get here
end
end
Если вы реорганизуете свой код, он должен выглядеть примерно так:
class SearchController < ApplicationController
def index
state = params[:state]
# fully define your @conn object
@conn = Faraday.new(url: "https://api.propublica.org") do |faraday|
faraday.headers["X-API-KEY"] = "<$MY-API-KEY>"
faraday.adapter Faraday.default_adapter
end
# now you can reference it
response = @conn.get("/congress/v1/members/house/#{state}/current.json")
results = JSON.parse(response.body, symbolize_names: true)[:results]
@members = results.map do |result|
Member.new(result)
end
end
end