Giter VIP home page Giter VIP logo

todos-api's People

Contributors

akabiru avatar hibaakroush avatar hmtanbir avatar looneym avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

todos-api's Issues

Error negative test with token invalid

How to handle error using fake token?

Original token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1MDI4NzkwNjl9.LHBLFECjHhvYBJL9n4zUydW94eDBpgz8g5MUiTsvuBU

Fake token: syJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1MDI4NzkwNjl9.LHBLFECjHhvYBJL9n4zUydW94eDBpgz8g5MUiTsvuBU

 http :3000/todos \ 
Authorization:'syJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1MDI4NzkwNjl9.LHBLFECjHhvYBJL9n4zUydW94eDBpgz8g5MUiTsvuBU'
HTTP/1.1 500 Internal Server Error
Content-Length: 11876
Content-Type: application/json; charset=UTF-8
X-Request-Id: aeb06724-91dc-463d-9999-f4d93abdd0aa
X-Runtime: 0.036293

{
    "error": "Internal Server Error", 
    "exception": "#<JWT::DecodeError: Invalid segment encoding>", 
    "status": 500, 
    "traces": {
        "Application Trace": [
            {
                "id": 5, 
                "trace": "app/lib/json_web_token.rb:15:in `decode'"

Error importing RequestSpecHelper, json is undefined

I've followed along with the tutorial but am getting an error running the specs after the tasks API is implemented. Specifically, my remaining failures are because json seems to be undefined, so the import of that helper module doesn't seem to be correct. My import looks like the following:

rails_helper.rb
....
ActiveRecord::Migration.maintain_test_schema!

# require database cleaner at the top level
require 'database_cleaner'

# [...]
# configure shoulda matchers to use rspec as the test framework and full matcher libraries for rails
Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end

# [...]
RSpec.configuration do |config|
  # [...]

  config.include RequestSpecHelper, type: :request

  # start by truncating all the tables but then use the faster transaction strategy the rest of the time.
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
    DatabaseCleaner.strategy = :transaction
  end

  # start the transaction strategy as examples are run
  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
  # [...]
end
....

I get the following error at the terminal:

NameError:
       undefined local variable or method `json' for #<RSpec::ExampleGroups::TasksAPI::POSTTasks::WhenTheRequestIsValid:0x007f844f093320>
       Did you mean?  JSON

Thanks in advance for any help!

Error in http_auth_header method of AuthorizeApiRequest

I've tried a full copy/paste of your file to ensure I didn't miss anything (I've reverted back to my version) and the same error persists.

expected ExceptionHandler::MissingToken with "Missing token", got #<TypeError: no implicit conversion of String into Integer>

This is being thrown on this line:

if headers['Authorization'].present?

Totally stumped on this!

Why do I have to get the current_user todos only?

I don't understand why did you get current_user.todos only, what if I want to allow the user to do anything as long as he's logged in? how can I achieve that with JWT instead of adding current_user to the controllers?

Logout

Any strategy to invalidate access ? expire the token?

Test case errors

Posts API POST /api/posts when the request is valid creates a post
Failure/Error: render json: post, status: status

 NoMethodError:
   undefined method `to_i' for {:status=>201}:Hash
   Did you mean?  to_s
                  to_a
                  to_h

I tried it with several changes. since it says it's an hash i did expect(response.status).to have_http_status(201)
but still didnt work.

Missing signout from the system

Hi,
I am wondering that no sign out process in this api.
It will better if user can sign out using nullification the authorization token.
Could you please add the process @akabiru ?

uninitialized constant RequestSpecHelper (NameError)

Hi,

As I was working through your tutorial, an error popped up blocking me from using bundle exec rspec. I have checked the gems and configuration file rails_helper.rb to make sure it is exactly the same as in your tutorial.

I've already tried to explore internet and look for solutions, but must of them are about editing spec_helper.rb (which doesn't explain why, because backtrace shows problem comes from rails_helper.rb; and spec_helper.rb is identical to the one in tutorial) and used rails versions are < 5.0.

Here is a full trace:

****/todos-api$ bundle exec rspec
*full path*/todos-api/spec/rails_helper.rb:73:in `block in <top (required)>': uninitialized constant RequestSpecHelper (NameError)
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core.rb:98:in `configure'
	from /home/beniusij/RubymineProjects/todos-api/spec/rails_helper.rb:37:in `<top (required)>'
	from /home/beniusij/RubymineProjects/todos-api/spec/models/item_spec.rb:1:in `require'
	from /home/beniusij/RubymineProjects/todos-api/spec/models/item_spec.rb:1:in `<top (required)>'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `block in load_spec_files'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `each'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `load_spec_files'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:100:in `setup'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:86:in `run'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:71:in `run'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:45:in `invoke'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/gems/rspec-core-3.5.4/exe/rspec:4:in `<top (required)>'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/bin/rspec:22:in `load'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/bin/rspec:22:in `<main>'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/bin/ruby_executable_hooks:15:in `eval'
	from /home/beniusij/.rvm/gems/ruby-2.4.1/bin/ruby_executable_hooks:15:in `<main>'

Gemfile:

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.0.rc1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
# gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
# gem 'rack-cors'

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem "rspec-rails", '~> 3.5'
end

group :development do
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
	gem 'factory_girl_rails', '~> 4.0'
	gem 'shoulda-matchers', '~> 3.1'
	gem 'faker'
	gem 'database_cleaner'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

spec/rails_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/core'
require 'spec_helper'
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
require 'database_cleaner'
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end

RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  config.include FactoryGirl::Syntax::Methods

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
    DatabaseCleaner.strategy = :transaction
  end

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
  # RSpec Rails can automatically mix in different behaviours to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post` in specs under `spec/controllers`.
  #
  # You can disable this behaviour by removing the line below, and instead
  # explicitly tag your specs with their type, e.g.:
  #
  #     RSpec.describe UsersController, :type => :controller do
  #       # ...
  #     end
  #
  # The different available types are documented in the features, such as in
  # https://relishapp.com/rspec/rspec-rails/docs
  config.infer_spec_type_from_file_location!

  config.include RequestSpecHelper, type: :request
  # Filter lines from Rails gems in backtraces.
  config.filter_rails_from_backtrace!
  # arbitrary gems may also be filtered via:
  # config.filter_gems_from_backtrace("gem name")
end

Versions:
Rails 5.1.0.rc1
Ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]

P.S. Fun tutorial, I hope to get this solved soon so I could finish the tutorial and wait for part 2! :)

Test case errors

Hi austin,

I have done the same thing as you have shown, but somehow my factory doesn't seem to be working properly. i have attached the test case error in the picture.
Hopefully you can tell me what's wrong with it.

Regards,
Dawa.
factory error
validation error

Running into troubles when trying to run test for Items test cases

I literally have no clue where I could be wrong. I followed your tutorial step-by-step and get this output from rspec on my POST test case:

Failure/Error: before { post "/posts/#{post_id}/items", params: {} }
     
     ArgumentError:
       wrong number of arguments (given 2, expected 0)

One more thing: I have renamed Todo model to Post.
Any ideas?

UPDATE: It seems that RSpec doesn't accept Post as model name, because of keyword post in your before { post ... } expectation inside of spec/requests/items_spec.rb

Possible typo on Part 1?

In Part 1, under the TodoItems API, i noticed that the RSpec "item_spec.rb" is actually stored under app/requests/.

Also I checked with the source code, there isn't such folder in App directory, so I believe this is a typo?

Errros in todos_spec at end of part two

At the end of part two, according to the tutorial, the code should look like:

    context 'when the request is invalid' do
      let(:valid_attributes) { { title: nil }.to_json }
      before { post '/todos', params: valid_attributes, headers: headers }

      it 'returns status code 422' do
        expect(response).to have_http_status(422)
      end

      it 'returns a validation failure message' do
        expect(response.body)
          .to match(/Validation failed: Created by can't be blank/)
      end
    end

However there are a couple of problems.

First, we are testing invalid parameters so we should name them as such:

    context 'when the request is invalid' do
      let(:invalid_attributes) { { title: nil }.to_json }
      before { post '/todos', params: invalid_attributes, headers: headers }

Also since we're now wrapping the error message in a Message object we need to deal with that and also expect the right attribute to be missing:

      it 'returns a validation failure message' do
        expect(json['message'])
          .to match(/Validation failed: Title can't be blank/)
      end

Thus the correct spec should look like:

    context 'when the request is invalid' do
      let(:invalid_attributes) { { title: nil }.to_json }
      before { post '/todos', params: invalid_attributes, headers: headers }

      it 'returns status code 422' do
        expect(response).to have_http_status(422)
      end

      it 'returns a validation failure message' do
        expect(json['message'])
          .to match(/Validation failed: Title can't be blank/)
      end
    end

Login issue

Hi Austin,

First, thanks a lot for your tutorials. It helps me a lot to understand the JWT in rails.

I have done the same thing (I change the email in user to phone_number), but somehow the login doesn't seem to be working properly. Everytime I logged in using postman, I got invalid credentials even though I put the right phone_number and password.

Hopefully you can tell me what I am doing wrong.

Regards,
Putra

Licensing

Thanks for a great tutorial!

I notice that you haven't got any licensing information about the code either here or on the scotch.io website. I'm guessing from the tutorial that you want others to use the code, but unfortunately the default copyright it has currently doesn't allow that.

Would you consider licensing this with a permissive license to allow others to build on it?

https://choosealicense.com/ is a good resource for helping choose the license you want. Rails itself is under an MIT license which could be easily altered for your use. :)

Adjustment for rails 5.2.0

Hi, Austin. Thanks for the great tutorial.

I found one adjustment for your tutorial. Since rails 5.2.0 doesn't generate secret.yml but credentials.yml.enc, the HMAC_SECRET in app/lib/json_web_token.rb should be

HMAC_SECRET = Rails.application.credentials.read

If the HMAC_SECRET still using secret_key_base, it will throw status 500 error with exception:

"#<TypeError: no implicit conversion of nil into String>

This adjustment for rails 5.2.0 only for this time. Again, I thank you for your great tutorials.

Failure/Error: expect(json['title']).to eq('Learn Elm')

Hi,
I got this error when run bundle exec rspec

Failures:

  1. Todos API POST /todos when the request is valid creates a todo
    Failure/Error: expect(json['title']).to eq('Learn Elm')

    NoMethodError:
    undefined method `[]' for nil:NilClass

Finished in 1.1 seconds (files took 3.14 seconds to load)
18 examples, 1 failure

Failed examples:

rspec ./spec/requests/todos_spec.rb:60 # Todos API POST /todos when the request is valid creates a todo

Could you please help me
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.