Sorry for the title, I'm too frustrated to come up with anything better right now.
I have a class, Judge, which has a method #stats. This stats method is supposed to send a GET request to an api and get some data as response. I'm trying to test this and stub the stats method so that I don't perform an actual request. This is what my test looks like:
describe Judge do
describe '.stats' do
context 'when success' do
subject { Judge.stats }
it 'returns stats' do
allow(Faraday).to receive(:get).and_return('some data')
expect(subject.status).to eq 200
expect(subject).to be_success
end
end
end
end
This is the class I'm testing:
class Judge
def self.stats
Faraday.get "some-domain-dot-com/stats"
end
end
This currently gives me the error: Faraday does not implement: get
So How do you stub this with faraday? I have seen methods like:
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
stub.get('http://stats-api.com') { [200, {}, 'Lorem ipsum'] }
end
But I can't seem to apply it the right way. What am I missing here?
Note that Faraday.new returns an instance of Faraday::Connection, not Faraday. So you can try using
allow_any_instance_of(Faraday::Connection).to receive(:get).and_return("some data")
Note that I don't know if returning "some data" as shown in your question is correct, because Faraday::Connection.get should return a response object, which would include the body and status code instead of a string. You might try something like this:
allow_any_instance_of(Faraday::Connection).to receive(:get).and_return(
double("response", status: 200, body: "some data")
)
Here's a rails console that shows the class you get back from Faraday.new
$ rails c
Loading development environment (Rails 4.1.5)
2.1.2 :001 > fara = Faraday.new
=> #<Faraday::Connection:0x0000010abcdd28 #parallel_manager=nil, #headers={"User-Agent"=>"Faraday v0.9.1"}, #params={}, #options=#<Faraday::RequestOptions (empty)>, #ssl=#<Faraday::SSLOptions (empty)>, #default_parallel_manager=nil, #builder=#<Faraday::RackBuilder:0x0000010abcd990 #handlers=[Faraday::Request::UrlEncoded, Faraday::Adapter::NetHttp]>, #url_prefix=#<URI::HTTP:0x0000010abcd378 URL:http:/>, #proxy=nil>
2.1.2 :002 > fara.class
=> Faraday::Connection
Coming to this late, but incase anyone else is too, this is what worked for me - a combination of the approaches above:
let(:json_data) { File.read Rails.root.join("..", "fixtures", "ror", "501100000267.json") }
before do
allow_any_instance_of(Faraday::Connection).to receive(:get).and_return(
double(Faraday::Response, status: 200, body: json_data, success?: true)
)
end
Faraday the class has no get method, only the instance does. Since you are using this in a class method what you can do is something like this:
class Judge
def self.stats
connection.get "some-domain-dot-com/stats"
end
def self.connection=(val)
#connection = val
end
def self.connection
#connection ||= Faraday.new(some stuff to build up connection)
end
end
Then in your test you can just set up a double:
let(:connection) { double :connection, get: nil }
before do
allow(connection).to receive(:get).with("some-domain-dot-com/stats").and_return('some data')
Judge.connection = connection
end
I ran into the same problem with Faraday::Adapter::Test::Stubs erroring with Faraday does not implement: get. It seems you need to set stubs to a Faraday adapter, like so:
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
stub.get("some-domain-dot-com/stats") { |env| [200, {}, 'egg'] }
end
test = Faraday.new do |builder|
builder.adapter :test, stubs
end
allow(Faraday).to receive(:new).and_return(test)
expect(Judge.stats.body).to eq "egg"
expect(Judge.stats.status).to eq 200
A better way to do this, rather than using allow_any_instance_of, is to set the default connection for Faraday, so that Faraday.get will use the connection you setup in your tests.
For example:
let(:stubs) { Faraday::Adapter::Test::Stubs.new }
let(:conn) { Faraday.new { |b| b.adapter(:test, stubs) } }
before do
stubs.get('/maps/api/place/details/json') do |_env|
[
200,
{ 'Content-Type': 'application/json' },
{ 'result' => { 'photos' => [] } }.to_json
]
end
Faraday.default_connection = conn
end
after do
Faraday.default_connection = nil
end
Related
My controller:
class V1::SendContractController < V1::BaseController
def create
byebug
bride_membership = Wedding.find(send_params[:weddingId]).bride_memberships[0]
SendBrideContractJob.perform_now(bride_membership, send_params[:contractId])
render json: { enqueuedDelivery: true }, status: :ok
end
private
def send_params
params
.require(:weddingId)
.permit(:contractId)
end
end
My params
Parameters: {"weddingId"=>4, "contractId"=>20, "send_contract"=>{"weddingId"=>4, "contractId"=>20}}
The error
NoMethodError (undefined method `permit' for 4:Integer):
But then when I byebug it I get what I want!
(byebug) params
<ActionController::Parameters {"weddingId"=>4, "contractId"=>20, "controller"=>"v1/send_contract", "action"=>"create", "send_contract"=>{"weddingId"=>4, "contractId"=>20}} permitted: false>
(byebug) params[:weddingId]
4
And I'm using axios with an interceptor to take care of formatting issues:
axios.interceptors.request.use((config) => {
if(config.url !== "/authentications") {
config.paramsSerializer = params => {
// Qs is already included in the Axios package
return qs.stringify(params, {
arrayFormat: "brackets",
encode: false
});
};
axios.defaults.headers.common['Authorization'] = `Bearer ${store.state.token.token}`
config.headers.common['Authorization']= `Bearer ${store.state.token.token}`
axios.defaults.headers.common['Accept'] = 'application/vnd.bella.v1+json'
config.headers.common['Accept'] = 'application/vnd.bella.v1+json'
return config
}
return config
})
I believe that require gives you the object at the key you provide to do further permit and / or require calls.
Perhaps you could try (not tested):
params.require(:weddingId)
params.permit(:weddingId, :contractId)
Edit: there's this too: Multiple require & permit strong parameters rails 4
Refer to this documentation and question.The require ensures that a parameter is present. If it's present, returns the parameter at the given key, otherwise raises an ActionController::ParameterMissing error.
p = { "weddingId"=>4, "contractId"=>20 }
ActionController::Parameters.new(p).require(:weddingId)
# 4
p = { "weddingId"=>nil, "contractId"=>20 }
ActionController::Parameters.new(p).require(:weddingId)
# ActionController::ParameterMissing: param is missing or the value is empty: weddingId
If you want to make sure :weddingId is present:
def contract_params
params.require(:weddingId)
params.permit(:contractId, :weddingId)
end
BTW, SendContractController is better called ContractsController.
I'm trying to test simple class in my Ruby 2.5.0 app:
source/parsers/jira_parser.rb
module Parsers
class JiraParser
def initialize(event)
payload = event['body']
#event = JSON.parse(payload)
end
def call
{
reporter_email: reporter_email,
reporter_name: reporter_name,
ticket_number: ticket_number,
description: description
}
end
private
attr_reader :event
def reporter_email
event.dig('issue', 'fields', 'reporter', 'emailAddress')
end
# other methods from call are pretty much the same as `reporter_email`
With below specs:
spec/source/parsers/jira_parser_spec.rb
require 'spec_helper'
RSpec.describe Parsers::JiraParser do
describe 'call' do
subject(:hash_creation) { described_class.new(event).call }
let(:reporter_name) { 'john.doe' }
let(:reporter_email) { 'john.doe#example.com' }
let(:description) { 'This is a test description' }
let(:event) do
{
'body' => {
'issue': {
'key': 'TEST-Board-123',
'fields': {
'reporter': {
'displayName': reporter_name,
'emailAddress': reporter_email
},
'description': description
}
}
}
}
end
it { expect(hash_creation).to be_success }
end
end
But I've got an error:
NameError:
uninitialized constant Parsers
./spec/source/parsers/jira_parser_spec.rb:5:in `'
No examples found.
Should I add something to my rspec_helper to make it works?
Right now it's pretty basic:
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
end
I understand this is just Ruby, no Rails, hence there's no magic involved. You need to make a source file available in spec file, so you have to put on the top something like:
require_relative '../../../source/parsers/jira_parser
Hello I am still pretty new so this might help but I believe that you need to require JiraParser
require 'jira_parser'
require 'jira_parser/parser'
This might work but the error is because you are trying to use a parser that is not accessible in your current code.
Ok I figured out - all I had to do was to add -I source inside the .rspec file to will load all tested classes. So in my case .rspec will look like below:
.rspec
--require spec_helper
-I source
I want to implement rspec with expect. I tried this:
RSpec:
describe WechatRequestBuilder do
let(:request_builder) { described_class.new(env: 'test_env') }
let(:trx_types) { ['wechat'] }
let(:trx_type) { 'wechat' }
let(:gateway) { 'wechat' }
let(:currency) { 'CNY' }
let(:base_params) { request_builder.send(:base_params) }
it_behaves_like 'request builder', true
context '#submit!' do
it "sends test transactions" do
allow(request_builder).to receive(:process_trx).with(trx_types, gateway)
binding.pry
request_builder.submit!
expect(request_builder.submit!).to receive(:process_trx).with(trx_types, gateway)
end
end
end
Request modifier:
class RequestModifier
def get_trx_type(request_body)
doc = Nokogiri::XML(request_body)
doc.search("transaction_type").first.text
end
end
I tried to find some object with binding.pry but without a luck:
[1] pry(#<RSpec::ExampleGroups::WechatRequestBuilder::Submit>)> request_builder
=> #<WechatRequestBuilder:0x007ffc1af4fd80 #env="test_env", #request_modifier=#<RequestModifier:0x007ffc1af4fd30>>
Can you give e some example based on the above code what should I configure as 'expect'? Currently I get:
(nil).process_trx(["wechat"], "wechat")
expected: 1 time with arguments: (["wechat"], "wechat")
received: 0 times
I'm trying to DRY my RSpec request specs by using shared contexts. I'd like to share let variables between shared contexts so that they inherit and extend from one another.
Rspec.shared_context 'JSON request' do
let(:headers) do
{
'Accept' => 'application/json'
}
end
end
Rspec.shared_context 'Authenticated request' do
let(:headers) do
super().merge('Authorization' => "Bearer #{token}")
end
end
Rspec.describe 'user management' do
let(:token) { create(:oauth_token) }
include_context 'JSON request'
include_context 'Authenticated request'
it 'responds with a 200 ok' do
get '/user', headers: headers
expect(response).to have_http_status(:ok)
end
end
Declaring token works as expected, but using super() to override headers returns a NoMethodError suggesting super() is nil.
I'm not aware of a way to refer to the currently defined value of a let variable in a let block. (When I try it I get "stack level too deep".) I'd do what you're trying to do this way:
Rspec.shared_context 'JSON request' do
let(:common_headers) do
{
'Accept' => 'application/json'
}
end
let(:headers) { common_headers }
end
Rspec.shared_context 'Authenticated request' do
let(:headers) do
common_headers.merge('Authorization' => "Bearer #{token}")
end
end
You can use super() to get the value of a predefined let:
RSpec.shared_context 'common' do
let(:foo) { 'foo' }
end
RSpec.describe 'test' do
include_context 'common'
context 'reversed' do
let(:foo) { super().reverse }
it 'works' do
expect(foo).to eq('oof')
end
end
end
Is there a way to use map and the (lotus)router namespacing together? Below is a sample config.ru I'm trying to get running as a demo.
require 'bundler'
Bundler.require
module Demo
class Application
def initialize
#app = Rack::Builder.new do
map '/this_works' do
run Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["this_works"]]}
end
map '/api' do
run Lotus::Router.new do
get '/api/', to: ->(env) { [200, {}, ['Welcome to Lotus::Router!']] }
get '/*', to: ->(env) { [200, {}, ["This is catch all: #{ env['router.params'].inspect }!"]] }
end
end
end
end
def call(env)
#app.call(env)
end
end
end
run Demo::Application.new
Your problem is due to the precedence of do..end in method calls. In your code the section
run Lotus::Router.new do
get '/api/', to: ->(env) { [200, {}, ['Welcome to Lotus::Router!']] }
get '/*', to: ->(env) { [200, {}, ["This is catch all: #{ env['router.params'].inspect }!"]] }
end
is parsed by Ruby as
run(Lotus::Router.new) do
get '/api/', to: ->(env) { [200, {}, ['Welcome to Lotus::Router!']] }
get '/*', to: ->(env) { [200, {}, ["This is catch all: #{ env['router.params'].inspect }!"]] }
end
In other words the block is passed to run, not to Lotus::Router.new as you intended, and run simply ignores the block.
To fix it you need to ensure the block is associated with the constructor of the router rather than the call to run. There are a couple of ways to do this. You could use {...} rather than do...end, as that has a higher precedence:
run Lotus::Router.new {
#...
}
An alternative would be to assign the router to a local variable, and use that as the argument to run:
router = Lotus::Router.new do
#...
end
run router