Sending JSON as an attribute in a RSpec Request Test

I haven’t posted in quite a while. Been working with a lot of RSpec request testing for controllers, graphql, and active admin. (Never forget the S in RSpec is capitalized – that would have saved me a lot of pain!!)

My current trouble was sending an attribute that required a json value to an active admin create route via RSpec Request. I tried a whole bunch of things, but the solution is sooo simple, (too simple for the time spent on it) that I had to post it in case I needed to look up what I did again.

I just had to add .to_json on that specific attribute requiring json.

  let(:valid_attributes) do
    attributes_for(
      :model,
      content: {"key"=>"value"}.to_json
    )
  end

I hope this helps someone 🙂

I need to start posting more, just when you find the solution after debugging for so many hours it feels too simple to post about. Like I should have known that already! But I think we all have those moments!

Happy Programming 🙂

Pushing an existing local folder to Github

Hey, I’ve finally learned how to do something that has been bugging me for a while.

I never got it straight on how to push an existing folder of code on my computer to a new repository on Github.

I know it’s super simple, but I was always mid project and didn’t have time to look at it, so I would create a new Github Repository on www.github.com and then clone it down to my computer, and then copy all my existing files into it. Pretty silly, right?

So today was the day to do it right! And it’s actually embarrassingly simple.

Run the following commands from your terminal in your project’s directory: git init, git add . and git commit -m "initial commit"

Then logon to github.com, click on new repository https://github.com/new, and add one without a readme or licensing. This will create a completely empty repository.

It will take you to a quick setup page:

And you copy the code from …or push an existing repository from the command line

and paste that into your terminal, and now your local repository is connected to your github repository, and you push and pull like regular.

UPDATE: I just learned of a new CLI from homebrew called hub which helps us with this – https://hub.github.com/.

Make sure hub is installed –

$ brew install hub
# alias it as git $ alias git=hub 
$ git version git version 2.1.4 hub version 2.2.0  ← it works!

then after the initial commit run

$ git create -d "My new thing"
$ git push origin master

And you’ll never need to leave your terminal again (as long as you know your github password)!

How fun it is to be a lazy programmer 🙂

Dispatching Redux

When I think of redux this is what comes to mind:

And that’s not because I was ready to have my brain checked when starting to learn React/Redux 🙂

I am writing this post to explain to you how I think of React/Redux, and how it helped me better understand it, and I hope it can help you too!

This is not a detailed walk through, for tutorials on React/Redux I can recommend:

Among many of the fabulous resources out there people have taken the time out to help us understand this framework.

So now back to my ambulances…

If we want to have a function that will not be called on load, but rather upon an action — for example an onClick function, we cannot put the () after the function as that will call it as soon as the page loads it. We can’t put the function without the () because that will just show what’s contained in the function instead of ever running it. We need to somehow bind that function to the event so it can be triggered exactly when we want it to with the applicable event/data.

In redux to accomplish this we  dispatch the function. Here is a code example from my repo – https://github.com/mxdavis/timer-billing-client/

import {removeTask} from '../../redux/actions/tasks/tasks'

....

  handleDelete = event => {
    event.preventDefault();
    ...
    this.props.removeTask(this.state)
}

render(){
  return(
     ...
      <div className="uk-width-2-2 uk-text-center">
         <button
           onClick={this.handleDelete} 
           type="delete"
           value="Delete Task"
           >X</button>
        </div>
      ...
   )
}

...

const mapDispatchToProps = dispatch => {
  return bindActionCreators(
    { fetchClients, addTask, removeTask }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(AddTask);

 

Here we have the a delete button that dispatches an action removeTask onClick. Since I use mapDispatchToProps I do not need to put dispatch(removeTask(this.state)) instead if I use this.props.removeTask(this.state), the mapDispatchToProps already bound dispatch to removeTask and I can access it through props.

This function is an action and looks like so:

export function removeTask(task){
  return {
    type: 'REMOVE_UNBILLED_TASK',
    task
  }
}

The file was able to find it, because I had imported it previously (see the top line of the previous code snippet). I could have had this function locally in the folder, but to keep the file from getting too heavy I put it in an actions folder.

Now this action is being dispatched from the emergency call center to all the medics who have their radios always on waiting to accept the signal. And the medic in the right area that fits the type needed responds to the action and does what it is told to do.

This is where the reducers come in.

The reducers are set up in the store (normally through a combinedReducers, as there are frequently more than one reducer). Here is an example of my file that sets up redux store:

import {createStore, applyMiddleware, combineReducers } from 'redux'
import thunk from 'redux-thunk'

import clients from '../reducers/clients/clients'
import tasks from '../reducers/tasks/tasks'
import fetchingData from '../reducers/fetchingData'

const reducers = combineReducers({
  tasks, clients, fetchingData
})

const middleware = [thunk]

export default createStore(
  reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), 
  applyMiddleware(...middleware)
)

 

The combineReducers is combining all my reducers, and we pass this into createStore.

What this does is give the reducers each their own radio that is turned on and ready to listen when an action is being called just like when a person starts working as a medic he is given a radio that he needs to leave on and always listen to.

If you put a debugger in a reducer, you will see that it is called each time the page/app renders, even if the action never called that particular one, or if even any action is called at all.

Reducers are case statements looking for a string that matches the action.type that the action sent out.

With each state update, it checks to see if the action.type has been called, and if it does it will run the code inside.

Back to our analogy, when a medic’s radio hits based on certain criteria, he will receive the follow up instructions, while everyone else’s radio will stay silent as they do not need to be disturbed yet. If we had all our medics responding to every call they would be running all over the place, and not actually showing up to anyone on time and in an efficient manner. And not to mention, they’d probably all quit, and work for a more efficient team that knew how to alert only medics in the vicinity or medics with the equipment necessary for the call…

Here is what my reducer looks like that will match the string ‘REMOVE_UNBILLED_TASK’:

export default function tasks(state = {
    unbilled_tasks: [], 
    billed_tasks: []
}, action) {
  switch (action.type) {
  ...
    case 'REMOVE_UNBILLED_TASK':
      const tasksWithoutDeletedTask = state.unbilled_tasks.filter(t => t.task_id !== action.task.task_id)
      return Object.assign({}, state, {unbilled_tasks: tasksWithoutDeletedTask})
    default:
      return state;
  }
};

 

Always remember that since every reducer function gets called with each render we need to include a default option in our case statement that returns the current state, so that we do not end up with an empty state each time the page updates.

Keep this in mind when creating your reducers.

So to sum up my analogy, our medics/reducers always have their radios on waiting to be called, and this we set up by creating the redux store with our combinedReducers (unless we have only one reducer then we just put that one reducer in the store). The functions from the component dispatch actions only when they are triggered, and not upon load of the page (like onClick, or onChange..), which our component (medical center) sends the action.types to the correct (medic) reducer (instead of running all actions on load, and sending all medics on every call which would be extremely inefficient and time consuming!).

I hope I was able to help some people better understand the redux cycle. This was my first react/redux project and this concept really helped getting me started.

Heroku Deploy with Rails App

With my recent rails project at the Flatiron School, I deployed to heroku and learned a few cool things.

I found this video extremely helpful for the deploy, and set up of postgres (and you get a funny blooper at the end!):

Really useful advice I was given with heroku was to deploy early, and frequent so any bugs can be fixed as they happen instead of having to figure them out and make major changes because the bug is so embedded in the app that was working locally.

If you don’t want things going live immediately you can add a staging environment – https://devcenter.heroku.com/articles/multiple-environments.

You run heroku rake db:migrate, heroku rake db:seed to set up your database and seed your data.

You cannot drop a database in heroku, like you would in rails so you need to do heroku pg:reset

To drop into the rails console run: heroku run rails console. I found this super helpful to edit existing data in my databases, and run database queries.

You can set up configed vars for private keys and the like:

$ heroku config:set GITHUB_USERNAME=joesmith
Adding config vars and restarting myapp... done, v12
GITHUB_USERNAME: joesmith

$ heroku config
GITHUB_USERNAME: joesmith
OTHER_VAR:    production

$ heroku config:get GITHUB_USERNAME
joesmith

$ heroku config:unset GITHUB_USERNAME
Unsetting GITHUB_USERNAME and restarting myapp... done, v13

https://devcenter.heroku.com/articles/config-vars

And of course you’ll need to run heroku logs when you need to troubleshoot why something is not working as you’d expect.

UPDATE:  I just switched to a new computer and heroku did not recognize git push heroku master. It threw this nasty error at me:

fatal: ‘heroku’ does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Here’s the fix! heroku git:remote -a <yourapp> 

Then all works fine!

 

Happy Deploying!

 

Make SQL output look pretty in terminal

Here’s some commands to help make your sql output more readable in your command line:

output the name of each column

.header on

now we are in column mode, enabling us to run the next two .width commands

.mode column

adjusts and normalizes column width

.width auto

or

customize column width

.width <NUM1>, <NUM2>

Starting a gem file from scratch

If you are creating a new repository that is a future gem, here is the best way to do it:

bundle gem <gem_name>   #! Make sure gem_name is with “_” and not “-” because otherwise it will create each word between the “-” as a subfolder of lib, which can get pretty deep and unnecessary.

Now you can cd gem_name

Make sure to update you gem_name.gemspec and don’t forget to work on your gem and make it great!

Now you are ready to build your gem — update the lib/gem_name/version if this is not your first publish. Run gem build gem_name.gemspec 

Please note the gem file name has probably been changed from gem_name to gem-name-<version>.gem. You should see it as output after you have built your gem and in your directory as well.

Our gem has been created! If you want to publish to rubygems.org, make sure you have created your account. If this is your first time publishing a gem to rubygems.org you will be prompted for your credentials. If it’s not your first, your credentials are saved to your system.

Run gem push gem-name-<version>.gem and your gem should successfully register to rubygems.org

 

Sources:

http://bundler.io/rubygems.html

http://guides.rubygems.org/make-your-own-gem/

How to share a github repository with another user for pairing

Instructions for pairing while each github user has their own repository:

Each user should create their repository on github.

Each user should git remote add upstream copy_ssh_url_here_of_other_user

After doing the above if you run git remote -v you will see two remotes, one for your origin which is your respective github repo, and the other is for upstream which is your partner’s repo

When running git pull upstream master This will pull down any code your partner has pushed up to their github

When running git push this will push any changes you made to github, and allow your partner to git pull upstream master

If you will be working simultaneously create separate branches (git co -b <name-of-branch> and git pull and git merge <name-of-branch>  to master.

Happy Pairing!

 

 

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner