How to Create a Ghosted Dancer Effect in Adobe Photoshop

What You’ll Be CreatingAs we continue our series on effects inspired by music videos, one of the effects I find entrancingly beautiful is the ghosted figure effect. One of the best examples of this effect is seen throughout Adele’s “Send My Love” music…

View Tutorial: How to Create a Ghosted Dancer Effect in Adobe Photoshop

RSpec Testing for Beginners, Part 1

Are you new to Rails? New to coding? Curious about RSpec and how you can start testing? If so, this article should be a good starting point for you to get into test-driven development. It will explain to you the why and the how, and it will give you a survival kit to go on your first testing spree.

Topics

  • What’s the Point?
  • RSpec?
  • Getting Started
  • Running Tests
  • Basic Syntax
  • Four Phases of Tests
  • The Hard Thing About Testing

What’s the Point?

What is RSpec good for? RSpec is very useful on the Unit Test level, testing the finer details and the business logic of your app. That means testing the internals like models and controllers of your app. Tests that cover your views or feature tests which simulate more complete user flows, like purchasing an item, will not be the focus that RSpec is made for. RSpec does not make use of a web driver—as Capybara does, for example—that simulates a user’s interactions with an actual site or a representation of it.

Test-driven development (TDD), what’s the point? Well, that is not that easy to answer without feeding you some clichés. I hope this doesn’t sound evasive. I could provide a quick answer, but I want to avoid sending you home hungry after having only a small snack. The result of this little series about RSpec and testing should not only give you all the info to answer this question yourself but also provide you with the means and the understanding to get started with testing while feeling a bit confident already about the testing thing.

Beginners seem to have a harder time getting into RSpec and the TDD workflow than starting to get dangerous with Ruby or Rails. Why is that? I can only guess at this point, but on the one hand, the literature seems mostly focused on people who already have some programming skills under their belt, and on the other hand, learning all the stuff that is involved to have a clear understanding is a bit daunting. The learning curve can be quite steep, I suppose. For effective testing, there are a lot of moving parts involved. It’s a lot to ask for newbies who have just started to understand a framework like Rails to look at the process of building an app from the opposite perspective and learn a completely new API to write code for your code.

I thought about how to approach this “dilemma” for the next generation of coders who are just looking for a smoother start into this whole thing. This is what I came up with. I will break the most essential syntax down for you without assuming much more than basic knowledge of Ruby and a little bit of Rails. Instead of covering every angle possible and confusing you to death, we will go over your basic survival kit and try to paint the bigger picture. We will discuss the “How?” rather verbosely in order not to lose new coders along the way. The second part of the equation will be explaining the “Why?” 

If I’m lucky, you’ll get away with a good basis for more advanced books while feeling confident about the bigger picture. Ok now, let’s walk the walk! 

Benefits and Such

Let’s get back to the purpose of testing. Is testing useful for writing better quality apps? Well, this can be hotly debated, but at the moment I’d answer this question with a yes—I’m in the hipster TDD camp, I guess. Let’s see why tests provide your apps with a couple of benefits that are hard to ignore:

They check if your work functions as intended. Constantly validating that you are writing code that works is essential to the health of your application and your team’s sanity.

They test stuff you don’t want to test by hand, tedious checks that you could do by hand—especially when you’d need to check this all the time. You want to be as sure as possible that your new function or your new class or whatever does not cause any side effects in maybe completely unforeseen areas of your app. Automating that sort of thing not only saves you a ton of time but will also make testing scenarios consistent and reproducible. That alone makes them much more dependable than error-prone testing by hand.

We want to make sure the app behaves in a certain way, in an expected way. Tests can make sure to a pretty high degree that the way users interact with your app is functioning and avoiding bug scenarios that you were able to foresee. Tests check that your application works the way you designed it—and that it continues to work after you introduce modifications. This is especially important when your test suite informs you about failing scenarios about implementations of your app that might be old and therefore not exactly at the back of your brain anymore and not considered while you introduced some new functionality. In short, it helps to keep your app healthy and avoids introducing tons of bugs.

Automating tests make you actually test more frequently. Imagine if you have to test something for the 40th time for some reason. If it is only a bit time consuming, how easy will it be to get bored and skip the process altogether? These sort of things are the first step on a slippery slope where you can kiss a decent percentage of code coverage goodbye.

Tests work as documentation. Huh? The specs you write give other people on your teams a quick entry point to learn a new code base and understand what it is supposed to do. Writing your code in RSpec, for example, is very expressive and forms highly readable blocks of code that tell a story if done right. Because it can be written very descriptively while also being a very concise Domain Specific Language (DSL), RSpec hits two birds with one stone: not being verbose in its API and providing you with all the means to write highly understandable test scenarios. That’s what I always liked about it and why I never got really warm with Cucumber, which was solving the same issue in an overly client-friendly way, I think.

They can minimize the amount of code you write. Instead of spiking around like crazy, trying out stuff more freestyle, the practice of test-driving your code lets you write only the code that is necessary to pass your tests. No excess code. A thing you will often hear in your future career is that the best code is code you don’t have to write or something. Why? Well, most often, more elegant solutions involve lesser amounts of code and also, code that you don’t write—which might be unnecessary—won’t cause any future bugs and doesn’t need to be maintained. So writing the tests first, before you write the implementation, gives you a clear focus on which problem you need to solve next. Writing only code that is necessary, and not accidentally more, is maybe an underestimated side effect that TDD can provide you with. 

They have a positive effect on your design. To me, understanding this part turned on a light bulb and made me really appreciate the whole testing thing. When you write your implementations around very focused test scenarios, your code will most likely turn out to be much more compartmentalized and modular. Since we are all friends of DRY—“Don’t repeat yourself!”—and as little coupling between components in your app as possible, this is a simple but effective discipline to achieve systems which are designed well from the ground up. This aspect is the most important benefit, I think. Yes, the other ones are pretty awesome as well, but when tests also result in apps whose quality is better due to a refined design, I’d say Jackpot! 

It boils down to money as well. When you have a stable app that is easy to maintain and easy to change, you will save quite a bit of money in the long run. Unnecessary complexity can haunt projects easily, and motivation won’t be on an all-time high when your team has to fight your code because it’s brittle and badly designed. Good application design can absolutely support your business goals—and vice versa. Do you want to introduce some new features that are critical to your business, but you are constantly fighting your architecture because it was built on sand? Of course not, and we all have seen lots of examples of businesses that quickly disappeared for that exact reason. Good testing habits can be an effective line of defense for such situations. 

Another goal that is important is in respect to the quality of your code itself. The software you write should be easy to understand for other developers—as much as possible, at least. Your tests can really help to convey the functionality and intent of your application—and not only to other members on a team but to your future self as well. If you don’t touch a certain section of your code for quite a while, it will really be handy to refresh your memory of how and why you wrote a piece of software with the documentation that a tool such as RSpec provides—and RSpec does this really well, exceptionally actually.

Since your code will always change, refactoring your code will and should always be part of developing your software. And since change is so baked into this process, you need to make sure that these changes don’t generate unexpected side effects in surprising places. The test suite gives you a pretty tight-knit security net to feel more comfortable and free to refactor with gusto. This aspect, next to the design benefits TDD can provide you with, is my favorite benefit a test suite can help you with. Modifying and extending your code is such an essential component of innovating on your already released “product” that you need a tool that gives you as much freedom as possible with that process. I’m not sure if people who are critical of writing an extensive test suite are much concerned about this aspect.

You will have a good chance of building new stuff faster in later stages because the feedback from the test suite will give you feedback about your failures, bugs, and limitations—much faster than a human can test, of course. Plus, it will give you the confidence of working with a security net that becomes even more valuable the longer you go. 

In your apps, especially if they have grown significantly, you want to be able to trust your software. 100% code coverage sounds a lot sweeter when you have a site that is a couple of years old and touched by hundreds of developers. Being able to trust the new code you introduce and building on top of that is one of the blisses of software development that money can’t buy later on.

Getting Started

Terminal

rails new your_app -T

-T lets you skip Test Unit, the testing framework that comes with Rails.

Gemfile

group :development, :test do
  gem 'rspec-rails'
end

Terminal

bundle

After that we need to run a generator that comes with RSpec:

Terminal

rails generate rspec:install

Output

create  .rspec
create  spec
create  spec/spec_helper.rb
create  spec/rails_helper.rb

What this does is set up the basic structure for your RSpec tests within Rails. As you can see from the output above, this generator initialized a spec directory with a few files that you will need later. The .rspec file is a configuration file that we won’t need to manipulate for now. I just wanted to let you know what you have in front of you. The other files are self-explanatory, but I wanted to mention their differences.

  • spec_helper.rb is for specs that don’t depend on Rails.
  • rails_helper.rb, on the other hand, is for specs that do depend on it.

What is not obvious is that one of these files needs to be required on top of your spec files (test files) in order to run your tests. Let’s have a quick look! When you generate a model via: 

Terminal

rails generate model dummy_model name:string

Output

invoke  active_record
create    db/migrate/20160521004127_create_dummy_models.rb
create    app/models/dummy_model.rb
invoke    rspec
create    spec/models/dummy_model_spec.rb

Not only will Rails have created the associated _spec.rb files for you, your specs will also automatically have require 'rails_helper' by default on top of your spec files. That means you are ready to go, right away. 

spec/models/dummy_model_spec.rb

require 'rails_helper'

...

So with this setup, you can test your Rails app, your models for example, and RSpec will not get confused about model classes used in Rails. This is necessary to require whenever you need stuff like ActiveRecord, ApplicationController and so on. So this is your normal scenario and therefore should be your first logical choice as a beginner.

Requiring spec_helper.rb, on the other hand, will throw an error if you write tests that include business logic from your Rails app. In that scenario, RSpec would not know what you are talking about when you want to test some Rails model, for example. 

So long story super short, spec_helper does not load Rails—that’s it! Of course, you can go wild with configurations, but this is nothing I want you to be concerned about right now. Let’s focus on the basics, how to run tests and the syntax. That should suffice for starters. Let’s move on!

Running Tests

You are ready to run your tests. RSpec requires your test files to have a specific suffix like _spec to understand which files to run. If you use a generator, this is not a concern, but if you want to write test files on your own, this is how they need to end. So you will need to put a file like your_first_test_spec.rb in your spec directory. 

Using the generator for creating a dummy model already provided us with spec/models/dummy_model_spec.rb. Not bad! One thing left to do before the tests are ready: 

Terminal

rake db:migrate
rake db:test:prepare

These commands run your migration for the dummy model we generated above, and set up the test database with that model as well. Now we actually run the test:

Terminal

rake

The rake command will run all your tests, the complete test suite. Usually you should use this command when you have finished some feature and want to exercise the whole test suite.

Output

*
Pending: (Failures listed here are expected and do not affect your suite's status)

1) DummyModel add some examples to (or delete) /Users/vis_kid/projects/rspec-test-app/rspec-dummy/spec/models/dummy_model_spec.rb
   # Not yet implemented
   # ./spec/models/dummy_model_spec.rb:4

Finished in 0.00083 seconds (files took 1.94 seconds to load)

1 example, 0 failures, 1 pending

Congratulations! You just ran your first RSpec test. Not that bad, was it? Of course, this was a dummy test for now—with dummy test code generated by Rails. The more focused version of running your tests—you have actually a lot more options than only that—is to run an individual file, for example. Like this:

Terminal

bundle exec rspec spec/models/dummy_model_spec.rb

This will only run a single test file instead of the whole test suite. With larger applications that depend on a high amount of test files, this will become a real time saver. But in terms of saving time and test specificity, this is only scratching the surface, to be frank. I think we will cover more of how to shave off a significant amount of time while testing in the third article in this series. Let’s see how far we get!

The other way to exercise the whole test suite is by simply running rspec—with or without bundle exec, depending on your setup.

Terminal

bundle exec rspec

One more thing I should mention before we move on, you can also run only a specific subset of tests. Say you only want to run all of your tests for your model code:

Terminal

bundle exec rspec spec/models

Easy as that!

Basic Syntax

I recommend that we start with the bare basics and look into a few more options that RSpec provides in the next two articles. Let’s have a look at the basic structure of a test and dive into more advanced waters when we’ve got this one out of the way.

  • describe

This will be your bread and butter because it organizes your specs. You can reference strings or classes themselves:

Some Spec

describe User do

end

describe 'Some string' do

end

describe sections are the basic building blocks to organize your tests into logical, coherent groups to test. Basically, a scope for different parts of your application that you want to test.

Some Spec

describe User do
  ...
end

describe Guest do
  ...
end

describe Attacker do
  ...
end

A good tip is to tighten your scope even more. Since some classes will grow quite significantly, it’s not a good idea to have all the methods you want to test for one class in a single describe block. You can create multiple of these blocks, of course, and focus them around instance or class methods instead. To make your intent clearer, all you need is to provide the class name with an extra string that references the method you want to test.

Some Spec

describe Agent, '#favorite_gadget' do
  ...
end

describe Agent, '#favorite_gun' do
  ...
end

describe Agent, '.gambler' do
  ...
end

That way you get the best of both worlds. You encapsulate related tests in their representative groups while keeping things focused and at a decent size. For users very new to Ruby land, I should mention that # simply references an instance method while the dot . is reserved for class methods. Because they are inside strings, they have no technical implications here, but they signal your intent to other developers and your future self. Don’t forget the comma after the class name—it won’t work without it! In a minute, when we get to expect, I’ll show you why this approach is super convenient.

  • it

Within the scope of describe groups, we use another scope of it blocks. These are made for the actual examples under test. If you want to test the instance method #favorite_gadget on the Agent class, it would look like this:

Some Spec

describe Agent, '#favorite_gadget' do

  it 'returns one item, the favorite gadget of the agent ' do
    ...
  end

end

The string that you provide to the it block works as the main documentation for your test. Within it, you specify exactly what kind of behavior you want or expect from the method in question. My recommendation is not to go overboard and be too verbose about it but at the same time not to be overly cryptic and confuse others with overly smart descriptions. 

Think about what the smallest and simplest implementation of this part of the puzzle can and should accomplish. The better you write this part, the better the overall documentation for your app will be. Don’t rush this part because it’s just a string that can’t do any damage—at least not on the surface.

  • expect()

Now we’re getting more to the heart of things. This method lets you verify or falsify the part of the system you want to test. Let’s go back to our previous example and see it in (limited) action:

Some Spec

describe Agent, '#favorite_gadget' do

  it 'returns one item, the favorite gadget of the agent ' do
    expect(agent.favorite_gadget).to eq 'Walther PPK' 
  end

end

expect() is the “new” assertion syntax of RSpec. Previously we used should instead. Different story, but I wanted to mention it in case you run into it. expect() expects that you provide it with an object and exercise whatever method under test on it. Finally, you write the asserted outcome on the right side. 

You have the option to go the positive or negative route with .to eq or .not_to eq for example (eq being short for equal of course). You can always turn the logic around—whatever suits best your needs. Let’s run this nonsensical test and focus on the output that we got as a result of our test setup:

Terminal

rspec spec/models/agent_spec.rb

Output

Failures:

  1) Agent#favorite_gadget returns one item, the favorite gadget of the agent 
     Failure/Error: expect(agent.favorite_gadget).to eq 'Walther PPK'

Reads pretty nice, doesn’t it? **"Agent#favorite_gadget returns one item, and the favorite gadget of the agent"** tells you all you need to know:

  • the class involved
  • the method under test
  • the expected outcome

If we had left off the string that describes the method in the describe block, then the output would have been a lot less clear and readable:

Some Spec

describe Agent do

  it 'returns one item, the favorite gadget of the agent ' do
    expect(agent.favorite_gadget).to eq 'Walther PPK' 
  end

end

Output

Failures:

  1) Agent returns one item, the favorite gadget of the agent 
     Failure/Error: expect(agent.favorite_gadget).to eq 'Walther PPK'

Sure, there are other ways to circumvent and deal with this—passing this info via your it block, for example—but the other approach is just simple and works. Whatever makes your blood flow, of course!

Four Phases of a Test

Best practices in testing recommend that we compose our tests in four distinct phases:

  • test setup
  • test exercise
  • test verification
  • test teardown

These four phases are mostly for readability and to give your tests a conventional structure. It’s a so-called testing pattern, basically, a practice that the community widely agreed upon to be useful and recommended. This whole patterns topic is a deep rabbit hole, so know that I’ll leave out a bunch so as not to confuse the beginners among you to death. 

Setup

During setup, you prepare the scenario under which the test is supposed to run. In most cases, this will include data needed to be ready for some kind of exercise. Little tip: don’t overcomplicate things, and set up only the minimum amount necessary to make the test work.

agent = Agent.create(name: 'James Bond')
mission = Mission.create(name: 'Moonraker', status: 'Briefed')

Exercise

This part actually runs the thing that you want to test in this spec. Could be as simple as:

status = mission.agent_status

Verify

Now you verify if your assertion about the test is being met or not. So you test the system against your own expectations.

expect(status).not_to eq 'MIA')

Teardown

The framework takes care of memory and database cleaning issues—a reset, basically. There’s nothing for you to handle at this point. The goal is to get back a pristine state to run new tests without any surprises from the currently running ones. Let’s see what this would mean in a dummy example:

Some Spec

describe Agent, '#favorite_gadget' do

  it 'returns one item, the favorite gadget of the agent ' do
  # Setup
    agent = Agent.create(name: 'James Bond')
    q = Quartermaster.create(name: 'Q') 
    q.technical_briefing(agent)

  # Exercise    
    favorite_gadget = agent.favorite_gadget
  
  # Verify
    expect(favorite_gadget).to eq 'Walther PPK' 

  # Teardown is for now mostly handled by RSpec itself
  end

end

As you can see, in this example we separated the exercise and verify phases clearly from each other, whilst in the other dummy examples above, expect(agent.favorite_gadget).to eq 'Walther PKK, we mixed both phases together. Both are valid scenarios and have their place. Also, the new lines help to visually separate how the test is structured.

The Hard Thing About Testing

Now comes the hard part, what to test and how. In my opinion, this is the aspect of testing that is most confusing to newcomers—and understandably so! You are new to the language and framework and often don’t even know yet what you don’t know. How do you write tests for that? Very good question. 

I’ll be very frank, you don’t—most likely—and you won’t for quite a while. Getting comfortable with this stuff takes a while. When you have a mentor or attend some boot camp and such, you have the opportunity to directly learn from experienced people. In that case, your progress in this department will be different, of course.

On the other hand, if—like so many others out there—you are teaching yourself this stuff, patience will be key. Reading all the books and articles certainly gets you in the right direction, but I think that testing needs a lot of more advanced puzzle pieces in place in order for you to make complete sense and, maybe even more important, before you feel comfortable with it. 

The “good” news is that this is not unusual and we all have been there. Perseverance is important. You can do this, it’s no rocket science, but it will take a while until you can write an application effectively from the other way around—from the perspective of tests, I mean. For now, keep pushing, have fun, make mistakes, write apps, copy tutorials and whatnot, until the light bulb goes off.

Final Thoughts

When you write your individual tests, you want to make their objects do the simplest thing possible to achieve your goal—highly focused tests are really key. You want to design your application via very simple steps and then follow the errors your test suite is providing you with. 

Only implement what is necessary to get the app green. Not more, not less! That’s the “driven” part in test-driven development. Your work is guided by the needs of your tests.

View Tutorial: RSpec Testing for Beginners, Part 1

RSpec Testing for Beginners, Part 2

The second article in this short series teaches you how to use various matchers that come with RSpec. It also shows you how to slice your test suite through tagging, how callbacks work, and how to extract some data. We expand a little on the basic survival kit from the first article and show you enough to be dangerous without too much rope to hang yourself.

Topics

  • Matchers
  • Let
  • Subjects
  • Callbacks
  • Generators
  • Tags

In the first article we spent quite a lot of time trying to answer the “why?” of testing. I suggest we get right back to the “how?” and spare ourselves any more context. We covered that part extensively already. Let’s see what else RSpec has to offer that you as a beginner can handle right away.

Matchers

So this is going to approach the heart of things. RSpec provides you with a ton of so-called matchers. These are your bread and butter when you write your expectations. So far you have seen .to eq and .not_to eq. But there is a much bigger arsenal to write your specs. You can test to raise errors, for truthy and falsy values, or even for specific classes. Let’s run down a few options to get you started:

  • .to eq
  • .not_to eq 

This tests for equivalence.

Some Spec

...

it 'some clever description' do
  expect(agent.enemy).to eq 'Ernst Stavro Blofeld'
  expect(agent.enemy).not_to eq 'Winnie Pooh'
end

...

Attention!

To keep things short, I packed two expect statements within one it block. It is good practice, though, to test only a single thing per test. This keeps things a lot more focused, and your tests will end up less brittle when you change things.

  • .to be_truthy
  • .to be true

Some Spec

...

it 'some clever description' do
  expect(agent.hero?).to be_truthy
  expect(enemy.megalomaniac?).to be true
end

...

The difference is that be_truthy is true when it’s not nil or false. So it will pass if the result is neither of these two—kind of “true-like”. .to be true on the other hand only accepts a value that is true and nothing else.

  • .to be_falsy
  • .to be false

Some Spec

...

it 'some clever description' do
  expect(agent.coward?).to be_falsy
  expect(enemy.megalomaniac?).to be false
end

...

Similar to the two examples above, .to be_falsy expects either a false or a nil value, and .to be false will only do a direct comparison on false.

  • .to be_nil
  • .to_not be_nil

And last but not least, this tests exactly for nil itself. I spare you the example.

  • .to match()

I hope you already had the pleasure of looking into regular expressions. If not, this is a sequence of characters with which you can define a pattern that you put between two forward slashes to search strings. A regex can be very handy if you want to look for broader patterns that you could generalize in such an expression.

Some Spec

...

it 'some clever description' do
  expect(agent.number.to_i).to match(/\d{3}/)
end

...

Suppose we’re dealing with agents like James Bond, 007, who are assigned three-digit numbers. Then we could test for it this way—primitively here, of course.

  • >
  • <
  • <=
  • >=

Comparisons come in handy more often than one might think. I assume the examples below will cover what you need to know.

Some Spec

...

it 'some clever description' do

  ...

  expect(agent.number).to be < quartermaster.number
  expect(agent.number).to be > m.number
  expect(agent.kill_count).to be >= 25 
  expect(quartermaster.number_of_gadgets).to be <= 5
end

...

Now, we are getting somewhere less boring. You can also test for classes and types:

  • .to be_an_instance_of
  • .to be_a
  • .to be_an

Some Spec

...

it 'some clever description' do
  mission = Mission.create(name: 'Moonraker')
  agent = Agent.create(name: 'James Bond')
  mission.agents << agent

  expect(@mission.agents).not_to be_an_instance_of(Agent)
  expect(@mission.agents).to be_a(ActiveRecord::Associations::CollectionProxy)
end

...

In the dummy example above, you can see that a list of agents that are associated with a mission are not of class Agent but of ActiveRecord::Associations::CollectionProxy. What you should take away from this one is that we can easily test for classes themselves while staying highly expressive. .to be_a and .to be_an do one and the same thing. You have both options available to keep things readable.

Testing for errors is also massively convenient in RSpec. If you are super fresh to Rails and not sure yet which errors the framework can throw at you, you might not feel the need to use these—of course, that makes total sense. At a later stage in your development, you will find them very handy, though. You have four ways to deal with them:

  • .to raise_error

This is the most generic way. Whatever error is raised will be cast in your net.

  • .to raise_error(ErrorClass)

That way you can specify exactly which class the error should come from.

  • .to raise_error(ErrorClass, "Some error message")

This is even more fine grained since you not only mention the class of the error but a specific message that should be thrown with the error.

  • .to raise_error("Some error message)

Or you just mention the error message itself without the error class. The expect part needs to be written a little bit differently, though—we need to wrap the part under text in a code block itself:

Some Spec

...

it 'some clever description' do
  agent = Agent.create(name: 'James Bond')
  
  expect{agent.lady_killer?}.to raise_error(NoMethodError)
  expect{double_agent.name}.to raise_error(NameError)
  expect{double_agent.name}.to raise_error("Error: No double agents around")
  expect{double_agent.name}.to raise_error(NameError, "Error: No double agents around")
end

...
  • .to start_with
  • .to end_with

Since we often deal with collections when building web apps, it’s nice to have a tool to peek into them. Here we added two agents, Q and James Bond, and just wanted to know who comes first and last in the collection of agents for a particular mission—here Moonraker.

Some Agent Spec

...

it 'some clever description' do
  moonraker = Mission.create(name: 'Moonraker')
  bond = Agent.create(name: 'James Bond')
  q = Agent.create(name: 'Q')
  moonraker.agents << bond
  moonraker.agents << q

  expect(moonraker.agents).to start_with(bond)
  expect(moonraker.agents).to end_with(q)
end

..
  • .to include

This one is also helpful to check the contents of collections.

Some Agent Spec

...

it 'some clever description' do
  mission = Mission.create(name: 'Moonraker')
  bond = Agent.create(name: 'James Bond')
  mission.agents << bond

  expect(mission.agents).to include(bond)
end

...
  • predicate matchers

These predicate matchers are a feature of RSpec to dynamically create matchers for you. If you have predicate methods in your models, for example (ending with a question mark), then RSpec knows that it should build matchers for you that you can use in your tests. In the example below, we want to test if an agent is James Bond:

Agent Model

class Agent < ActiveRecord::Base

  def bond?
    name == 'James Bond' && number == '007' && gambler == true
  end

  ...

end

Now, we can use this in our specs like so:

Some Agent Spec

...

it 'some clever description' do
  agent = Agent.create(name: 'James Bond', number: '007', gambler: true)

  expect(agent).to be_bond
end

it 'some clever description' do
  agent = Agent.create(name: 'James Bond')

  expect(agent).not_to be_bond
end

...

RSpec lets us use the method name without the question mark—to form a better syntax, I suppose. Cool, ain’t it?

Let

let and let! might look like variables at first, but they are actually helper methods. The first one is lazily evaluated, which means that it is only run and evaluated when a spec actually uses it, and the other let with the bang(!) is run regardless of being used by a spec or not. Both versions are memoized, and their values will be cached within the same example scope.

Some Spec File

describe Mission, '#prepare', :let do
  let(:mission)  { Mission.create(name: 'Moonraker') }
  let!(:bond)    { Agent.create(name: 'James Bond') }

  it 'adds agents to a mission' do
    mission.prepare(bond)
    expect(mission.agents).to include bond
  end
end

The bang version that is not lazily evaluated can be time-consuming and therefore costly if it becomes your fancy new friend. Why? Because it will set up this data for each test in question, no matter what, and might eventually end up being one of these nasty things that slow down your test suite significantly.

You should know this feature of RSpec since let is widely known and used. That being said, the next article will show you some issues with it that you should be aware of. Use these helper methods with caution, or at least in small doses for now.

Subjects

RSpec offers you the ability to declare the subject under test very explicitly. There are better solutions for this, and we will discuss the downsides of this approach in the next article when I show a few things you generally want to avoid. But for now, let’s have a look at what subject can do for you:

Some Spec File

describe Agent, '#status' do
  subject { Agent.create(name: 'Bond')  }

  it 'returns the agents status' do
    expect(subject.status).not_to be 'MIA'
  end
end

This approach can, on the one hand, help you with reducing code duplication, having a protagonist declared once in a certain scope, but it can also lead to something called a mystery guest. This simply means that we might end up in a situation where we use data for one of our test scenarios but have no idea anymore where it actually comes from and what it is comprised of. More on that in the next article.

Callbacks

In case you are not aware of callbacks yet, let me give you a brief heads up. Callbacks are run at certain specific points in the lifecycle of code. In terms of Rails, this would mean that you have code that is being run before objects are created, updated, destroyed, etc. 

In the context of RSpec, it’s the lifecycle of tests being run. That simply means that you can specify hooks that should be run before or after each test is being run in the spec file, for example—or simply around each test. There are a few more fine-grained options available, but I recommend we avoid getting lost in the details for now. First things first:

  • before(:each)

This callback is run before each test example.

Some Spec File

describe Agent, '#favorite_gadget' do

  before(:each) do
    @gagdet = Gadget.create(name: 'Walther PPK')
  end

  it 'returns one item, the favorite gadget of the agent ' do
    agent = Agent.create(name: 'James Bond')
    agent.favorite_gadgets << @gadget

    expect(agent.favorite_gadget).to eq 'Walther PPK'
  end

  ...

end

Let’s say you would need a certain gadget for every test you run in a certain scope. before lets you extract this into a block and prepares this little snippet for you conveniently. When you set up data that way, you have to use instance variables, of course, to have access to it among various scopes.

Attention!

Don’t get fooled by convenience in this example. Just because you can do this kind of stuff does not mean you should. I want to avoid going into AntiPattern territory and confuse the hell out of you, but on the other hand, I want to explain the downsides to these simple dummy exercises a bit as well. 

In the example above, it would be much more expressive if you set up the needed objects on a test-by-test basis. Especially on larger spec files, you can quickly lose sight of these little connections and make it harder for others to piece together these puzzles.

  • before(:all)

This before block runs only once before all the other examples in a spec file.

Some Spec File

describe Agent, '#enemy' do

  before(:all) do
    @main_villain = Villain.create(name: 'Ernst Stavro Blofeld')
    @mission = Mission.create(name: 'Moonraker')
    @mission.villains << @main_villain
  end

  it 'returns the main enemy Bond has to face in his mission' do
    agent = Agent.create(name: 'James Bond')
    @mission.agents << agent

    expect(agent.enemy).to eq 'Ernst Stavro Blofeld'
  end

  ...

end

When you remember the four phases of test, before blocks sometimes are helpful in setting something up for you that needs to be repeated on a regular basis—probably stuff that is a bit more meta in nature.

after(:each) and after(:all) have the same behavior but are simply run after your tests have been executed. after is often used for cleaning up your files, for example. But I think it’s a bit early to address that. So commit it to memory, know that it’s there in case you start needing it, and let’s move on to explore other, more basic things.

All of these callbacks can be placed strategically to fit your needs. Place them in any describe block scope that you need to run them—they don’t have to necessarily be placed on top of your spec file. They can easily be nested way inside your specs. 

Some Spec File

describe Agent do

  before(:each) do
    @mission = Mission.create(name: 'Moonraker')
    @bond = Agent.create(name: 'James Bond', number: '007')
  end

  describe '#enemy' do 
    before(:each) do
      @main_villain = Villain.create(name: 'Ernst Stavro Blofeld')
      @mission.villains << @main_villain
    end

    describe 'Double 0 Agent with associated mission' do
      it 'returns the main enemy the agent has to face in his mission' do
        @mission.agents << @bond

        expect(@bond.enemy).to eq 'Ernst Stavro Blofeld'
      end
    end 

    describe 'Low-level agent with associated mission' do
      it 'returns no info about the main villain involved' do
        some_schmuck = Agent.create(name: 'Some schmuck', number: '1024')
        @mission.agents << some_schmuck

        expect(some_schmuck.enemy).to eq 'That’s above your paygrade!'
      end
    end

    ...

    ...

    ...

  end
end

 As you can observe, you can place callback blocks at any scope to your liking, and go as deep as you need. The code in the callback will be executed within the scope of any describe block scope. But a little bit of advice: if you feel the need of nesting too much and things seem to get a little bit messy and complicated, rethink your approach and consider how you could simplify the tests and their setup. KISS! Keep it simple, stupid. Also, pay attention to how nicely this reads when we force these tests to fail:

Output

Failures:

  1) Agent#enemy Double 0 Agent with associated mission returns the main enemy the agent has to face in his mission
     Failure/Error: expect(@bond.enemy).to eq 'Ernst Stavro Blofeld'

       expected: "Ernst Stavro Blofeld"
            got: "Blofeld"

  2) Agent#enemy Low-level agent with associated mission returns no info about the main villain involved
     Failure/Error: expect(some_schmuck.enemy).to eq 'That’s above your paygrade!'

       expected: "That’s above your paygrade!"
            got: "Blofeld"

Generators

Let’s also have a quick look at what generators are provided by RSpec for you. You have already seen one when we used rails generate rspec:install. This little fella made setting up RSpec for us quick and easy. What else do we have?

  • rspec:model

Want to have another dummy model spec?

Terminal

rails generate rspec:model another_dummy_model

Output

create  spec/models/another_dummy_model_spec.rb

Quick, isn’t it? Or a new spec for a controller test, for example:

  • rspec:controller

Terminal

rails generate rspec:controller dummy_controller

Output

spec/controllers/dummy_controller_controller_spec.rb
  • rspec:view

The same works for views, of course. We won’t be testing any views like that, though. Specs for views give you the least bang for the buck, and it is totally sufficient in probably almost any scenario to indirectly test your views via feature tests. 

Feature tests are not a specialty of RSpec per se and are more suited to another article. That being said, if you are curious, check out Capybara, which is an excellent tool for that kind of thing. It lets you test whole flows that exercise multiple parts of your app coming together—testing complete features while simulating the browser experience. For example, a user who pays for multiple items in a shopping cart.

  • rspec:helper

The same generator strategy lets us also place a helper without much fuss.

Terminal

rails generate rspec:helper dummy_helper

Output

create  spec/helpers/dummy_helper_helper_spec.rb

The double helper_helper part was not an accident. When we give it a more “meaningful” name, you will see that RSpec just attaches _helper on its own.

Terminal

rails generate rspec:helper important_stuff

Output

create  spec/helpers/important_stuff_helper_spec.rb

A Word About Helpers

No, this directory is not a place to hoard your precious helper methods that come up while refactoring your tests. These would go under spec/support, actually. spec/helpers is for the tests that you should write for your view helpers—a helper like set_date would be a common example. Yes, complete test coverage of your code should also include these helper methods. Just because they often seem small and trivial doesn’t mean that we should overlook them or ignore their potential for bugs we want to catch. The more complex the helper actually turns out, the more reason you should have to write a helper_spec for it!

Just in case you start playing around with it right away, keep in mind that you need to run your helper methods on a helper object when you write your helper tests in order to work. So they can only be exposed using this object. Something like this:

Some Helper Spec

describe '#set_date' do

...

  helper.set_date

...

end

...

You can use the same kind of generators for feature specs, integration specs and mailer specs. These are out of our scope for today, but you can commit them to memory for future use:

  • rspec:mailer
  • rspec:feature
  • rspec:integration

A Look at Generated Specs

The specs we created via the generator above are ready to go, and you can add your tests in there right away. Let’s have a tiny look at a difference between specs, though:

spec/models/dummy_model_spec.rb

require 'rails_helper'

RSpec.describe DummyModel, type: :model do
  pending "add some examples to (or delete) #{__FILE__}"
end

spec/controllers/dummy_controller_controller_spec.rb

require 'rails_helper'

RSpec.describe DummyControllerController, type: :controller do
end

spec/helpers/dummy_helper_helper_spec.rb

require 'rails_helper'

RSpec.describe DummyHelperHelper, type: :helper do
  pending "add some examples to (or delete) #{__FILE__}"
end

It doesn’t need a wunderkind to figure out that they all have different types. This :type RSpec metadata gives you an opportunity to slice and dice your tests across file structures. You can target these tests a bit better that way. Say you want to have some sort of helpers only loaded for controller specs, for example. Another example would be that you want to use another directory structure for specs that RSpec does not expect. Having this metadata in your tests makes it possible to continue to use RSpec support functions and not trip up the test suite. So you are free to use whatever directory structure works for you if you add this :type metadata.

Your standard RSpec tests do not depend on that metadata, on the other hand. When you use these generators, they will be added for free, but you can totally avoid them as well if you don’t need them. 

You can also use this metadata for filtering in your specs. Say you have a before block that should run only on model specs, for example. Neat! For bigger test suites, this might come in very handy one day. You can filter which focused group of tests you want to run—instead of executing the whole suite, which might take a while. 

Your options extend beyond the three tagging options above, of course. Let’s learn more about slicing and dicing your tests in the next section.

Tags

When you amass a bigger test suite over time, it won’t just be enough to run tests in certain folders to run RSpec tests quickly and efficiently. What you want to be able to do is run tests that belong together but might be spread across multiple directories. Tagging to the rescue! Don’t get me wrong, organizing your tests smartly in your folders is key as well, but tagging takes this just a bit further.

You are giving your tests some metadata as symbols like “:wip”, “:checkout”, or whatever fits your needs.  When you run these focused groups of tests, you simply specify that RSpec should ignore running other tests this time by providing a flag with the name of the tags.

Some Spec File

describe Agent, :wip do

  it 'is a mess right now' do
    expect(agent.favorite_gadgets).to eq 'Unknown'
  end

end

Terminal

rspec --tag wip

Output

Failures:

  1) Agent is a mess right now
       Failure/Error: expect(agent.favorite_gadgets).to eq 'Unknown'

...

You could also run all kinds of tests and ignore a bunch of groups that are tagged a certain way. You just provide a tilde (~) in front of the tag name, and RSpec is happy to ignore these tests.

Terminal

rspec --tag ~wip

Running multiple tags synchronously is not a problem either:

Terminal

rspec --tag wip --tag checkout

rspec --tag ~wip --tag checkout

As you can see above, you can mix and match them at will. The syntax is not perfect—repeating --tag is maybe not ideal—but hey, it’s no biggie either! Yes, all of this is a bit more extra work and mental overhead when you compose the specs, but on the flip side, it really provides you with a powerful ability to slice up your test suite on demand. On bigger projects, it can save you a ton of time that way.

Final Thoughts

What you’ve learned so far should equip you with the absolute basics to play with tests on your own—a survival kit for beginners. And really do play and make mistakes as much as you can. Take RSpec and the whole test-driven thingie for a spin, and don’t expect to write quality tests right away. There are still a couple of pieces missing before you will feel comfortable and before you will be effective with it. 

For me, this was a bit frustrating in the beginning because it was hard to see how to test something when I hadn’t yet implemented it and didn’t fully understand how it would behave. 

Testing really proves whether you understand a framework like Rails and know how the pieces fit together. When you write tests, you will need to be able to write expectations for how a framework should behave. 

That is not easy if you’re just starting out with all of this. Dealing with multiple domain-specific languages—here RSpec and Rails, for example—plus learning the Ruby API can be confusing as hell. Don’t feel bad if the learning curve seems daunting; it will get easier if you stick with it. Making this light bulb go off won’t happen over night, but to me, it was very much worth the effort.

View Tutorial: RSpec Testing for Beginners, Part 2

Illustrator in 60 Seconds: How to Add a Long Shadow to Any Icon Using the Blend Tool

Welcome to our Illustrator in 60 Seconds series, in which you can learn an Illustrator skill, feature, or technique in just a minute!

Illustrator in 60 Seconds: How to Add a Long Shadow to Any Icon Using the Blend Tool

In today’s video, I’ll show you how easy it is to add a long shadow to any icon, using the versatile Blend Tool.

So if you want to create these sort of shadows but you don’t know how, this video should have you covered.

A Bit More Detail

Learn more about Adobe Illustrator on Envato Tuts+:

60 Seconds?!

This is part of a series of quick video tutorials on Envato Tuts+ in which we introduce a range of subjects, all in 60 seconds—just enough to whet your appetite. Let us know in the comments what you thought of this video and what else you’d like to see explained in 60 seconds!

View Tutorial: Illustrator in 60 Seconds: How to Add a Long Shadow to Any Icon Using the Blend Tool

Sketch Mirror in 60 Seconds

Sketch has a great feature called “Mirror” which allows you to preview, real-time, your work on an iPhone, iPad, or a browser. Let’s take a look at its features in sixty seconds!

A Bit More Detail

Learn more about Sketch on Envato Tuts+

60 seconds?!

This is part of a series of quick video tutorials on Envato Tuts+ web design. We’re aiming to introduce a range of subjects, all in 60 seconds–just enough to whet your appetite. Let us know in the comments what you thought of this video and what else you’d like to see explained in 60 seconds!

Subtitles/CC

Here you’ll find the content of the “captions.sbv” file, which we can use to add subtitles to the screencast. Turn subtitles on by clicking the Subtitles/CC button on the player–click the settings gear icon to select the language:

0:00:00.000,0:00:03.030
Sketch has a great feature called “Mirror”.

0:00:03.030,0:00:07.919
It allows you to get a real-time preview
of your work on an iPhone, iPad or a

0:00:07.919,0:00:13.799
browser. The iOS app is free–download it
from the app store, open it and Sketch

0:00:13.799,0:00:18.270
will show your device in the drop-down.
Click your device name to connect and

0:00:18.270,0:00:19.080
you’re done.

0:00:19.080,0:00:23.519
Sketch also generates an address that’s
available in your local network so you

0:00:23.519,0:00:28.349
can preview your work in the browser. Now,
regardless of how many connections you

0:00:28.349,0:00:32.610
have every change you’ll make in your
document will be reflected in your

0:00:32.610,0:00:38.520
browser or your device. Mirror also supports
multiple artboards which can be accessed

0:00:38.520,0:00:44.190
by swiping on your device or using the
navigation buttons in the browser. This

0:00:44.190,0:00:48.960
feature has so many great applications;
you can share your artboards live for

0:00:48.960,0:00:54.360
example with coworkers, or simply test
your design on a smartphone or tablet.

0:00:54.360,0:00:57.930
That was Sketch Mirror in 60 seconds.

0:00:57.930,0:00:59.280
I’m Adi Purdila, thanks for watching.

View Tutorial: Sketch Mirror in 60 Seconds

How to Create a Double Exposure Illustration in Adobe Photoshop

Final product image
What You’ll Be Creating

Double exposures are not just for photographers. Illustrators can also create this fun effect with a few of Photoshop’s tools.

So in this quick tip, learn how to create this double exposure bird, using the Pen Tool, Shape Tools, and resources from Envato Market.

1. Create the Bird Silhouette

Step 1

Create a 1950 x 1800 px document in Photoshop at 150 dpi. Copy and paste your animal reference onto the canvas. Here I’ll be using this bird stock from Envato Market for my silhouette.

Silhouette Bird Reference

Feel free to use any other animal silhouette for reference; just make sure the silhouette is clearly defined. Control-T to Free Transform the photo, resizing the bird so that it fits better onto the canvas.

Resize Your Reference to Fill the Canvas

Step 2

Select the Pen Tool (P) and set the Pen Tool Mode to Path.

Now begin tracing the bird. Adjust the shape to create the cleanest silhouette possible. When you’re finished, Right-Click to Fill Path with a light gray color (#bfbfbf). Then Delete the path and reference layer.

Create a Silhouette with the Pen Tool

2. Color the Bird

Create a New Layer and position it underneath the bird. Fill the layer using the Gradient Tool (G) with a black to dark brown color (#110d0d).

Select the silhouette layer and right-click to go to Blending Options. Create a Gradient Overlay using sunset colors with the following settings:

  • Blend Mode: Normal
  • Opacity: 91%
  • Style: Linear
  • Angle: -65 Degrees
  • Scale: 122%
Fill the Silhouette with a Gradient Overlay

3. Create the Landscape

Step 1

Right-click the bird silhouette and select Rasterize Layer Style. Now begin creating the hills of your landscape. Select the Pen Tool (P) and set the Mode to Shape. Create the foreground shape in a downward slant with a dark brown color (#241512).

Right-click to set the shape as a Clipping Mask to the silhouette; this will help to keep the shape within the outline of the bird. 

Create a Hill with the Pen Tool

Create two more separate shapes for the middle and background land. Set the fill for the middle shape to a medium brown (#452b26) and the background land to a light tan color (#8e665c). Set them both as Clipping Masks to the silhouette. Rename the layers Foreground, Middle, and Background for better organization.

Create A Landscape with the Pen Tool

Step 2

Using the Polygon Tool (U), create a triangle and Fill it with the same dark brown (#241512) from the foreground layer. Then use the Direct Selection Tool (A) to make the triangle taller to represent a tree.

Create Trees with the Polygon Tool

Again, set this shape as a Clipping Mask to the silhouette and position it on top of the foreground hill. Control-T to Free Transform the shape if you need to make it smaller, and position it in place.

Add Trees to your Landscape

Hold Control-J to duplicate the first tree. Create several more duplicates and position them along the hill. Resize them to make them smaller or taller for more variety. When you’re finished, select all the trees and the foreground hill shape, and then Right-click to Merge Shapes.

Add More Trees and Merge Shape Layers

Step 3

Follow the same steps with the middle hill. It helps if you keep an extra triangle lying around from the first batch so that you have uniform trees. Also make sure that all the trees match the color of the hill (#452b26) so that they blend seamlessly together.

Create Trees for Middle Hill

Step 4

Let’s add a couple more shapes to this scene. Continue to set all the future steps as Clipping Masks to your original silhouette. To show a large sun setting in the distance, use the Ellipse Tool (U) to create a circle behind the background hill. Fill the circle with a pale peach color (#fecfc5) and position it towards the right side of the bird.

Add the Sun with the Ellipse Tool

Next, let’s create some easy birds. Use the Ellipse Tool (U) to create a red circle, and then use it again to create a brown circle in front of the red one that is much shorter and wider. Merge the shapes together. Use the Direct Selection Tool (A) to select the front circle and hit Subtract Front Shape under Path Operations.

Create a Bird with the Ellipse Tool

When you’re finished, select the shape again and now hit Merge Shape Components, selecting Yes when prompted to turn the shape into a path. Now that you have one wing done, Control-T to Free Transform and rotate the shape to an angle. Then Control-J to create a duplicate and go to Edit > Transform > Flip Horizontal to create the second wing. Position it in place, and Merge the shapes together.

Creating a Bird with Simple Shapes in Photoshop

Duplicate the bird shape several times and resize it to fit into the scene. Scatter the birds around. Make sure the color is set to the same dark brown of the foreground hill. When you’re finished, Merge all the bird shapes together.

Add the Birds to the Scene

4. Final Touches

Step 1

Create a New Layer above the birds and set it as a Clipping Mask. Using the Brush Tool (B)paint sunlight coming from the sun using the same peach color with a Soft Round Brush. Set the Blend Mode of the layer to Vivid Light for a powerful effect.

Add Sunlight with Vivid Light and the Brush Tool

Step 2

Create another clipped layer above the sunlight. Select the Brush Tool (B) and use a Hard Round Brush at 100% Hardness to create tiny stars for the sky. Lower the size to 1–5 px and dot the sky with white stars.

Right-click the layer and select Blending Options. Add an Outer Glow with the following settings:

Create Stars with the Brush Tool and Outer Glow

Step 3

The sky could be a little darker. Create a New Layer set as a Clipping Mask to the bird and use the Gradient Tool (G) to create a Linear Gradient that moves downward from black to transparent. Set the Blend Mode to Overlay and adjust the Opacity to 70%.

Add Darkness with the Gradient Tool

Step 4

Last but not least, let’s add a few sparkly stars. Create a simple sparkle by using the Line Tool (U) to create a line with a Width of 5 px. Rasterize the shape, and then go to Filter > Blur > Motion Blur, and set the angle to -90 degrees and the Distance to 85 px.

Create a Simple Star Sparkle in Photoshop

Create a Duplicate of the line and Rotate it to create a cross. Finish the sparkle off by using the Brush Tool (B) at 0% Hardness to create a soft white dot in the middle.

Merge the layers together and place the sparkle on one of the stars. Duplicate the sparkle twice more, positioning them in the sky and Merging the layers together. When you’re finished, set the layer to Vivid Light.

Create a Double Exposure Illustration Tutorial by Melody Nieves

Conclusion

Now your landscape is ready to fly off into the sunset! With a few tools and the perfect silhouette, you can create a beautiful double exposure illustration in Adobe Photoshop.

I hope you’ve enjoyed this tutorial. Please feel free to leave any questions in the comments. For more tutorials like this, check out the ones below:

Final Result Double Exposure Bird Illustration
View Tutorial: How to Create a Double Exposure Illustration in Adobe Photoshop

7 Popular React Courses for JavaScript Developers

React is a JavaScript library for building user interfaces that has taken the web development world by storm. React is known for its blazing-fast performance and has spawned an ecosystem of thousands of related modules on NPM.

But with all this complexity, it can be hard to know where to start. So here are seven courses that will teach you everything you need to know. 

1. Modern Web Apps With React and Redux

In this course, Envato Tuts+ instructor Andrew Burgess will get you started building modern web apps with React and Redux. Starting from nothing, you’ll use these two libraries to build a complete web application. 

You’ll start with the simplest possible architecture and slowly build up the app, feature by feature. You’ll learn about basic concepts like tooling, reducers, and routing. You’ll also learn about some more advanced techniques like smart and dumb components, pure components, and asynchronous actions. 

By the end, you’ll have created a complete flashcards app for learning by spaced repetition.

Along the way, you’ll get a chance to sharpen your ES6 (ECMAScript 2015) skills and learn the patterns and modules that work best with React and Redux!

2. Getting Started With React.js

In this course, Envato Tuts+ instructor David East will cover everything you need to know to get up to speed with React. You’ll look at how React differs from other frameworks, before diving into some of the key concepts, applications, and best practices.

3. React Deep Dive: Build a React App With Webpack

Get ready for a deep dive into React.js with Pavan Podila. In this course you’ll build a complex app using libraries such as D3, React-Bootstrap, and FixedDataTable. 

By the end, you will understand how to start your own React projects, organize your code using React components, and bundle your app code with Webpack. You’ll also learn a professional dev workflow for React. You’ll walk away with a stronger understanding of React components and their lifecycle by learning how to wrap existing third-party libraries within React components.

4. Build a Social App With React Native

React Native, created by Facebook, lets you write native mobile apps in modern JavaScript. In this course, Markus Mühlberger will show you how to create a social application in React Native. You will learn how to build an app easily with a Firebase back-end. You’ll also learn some more advanced topics like sophisticated view routing, camera and photo library access, as well as how to use the device’s address book.

5. Building a Wiki With React and Firebase

In this course, Andrew Burgess will show you how to use React to build a multi-user web application from start to finish.

You’ll also learn how to use Firebase, a cloud-hosted data back-end for web and mobile applications, to implement a very simple JSON-based data store for the course project: a live collaborative wiki.

6. Build a Microblogging App With Flux and React

There’s a lot of talk about Flux these days. If you haven’t had a chance to try it yet, you might wonder what you’re missing!

Flux is an architecture for React applications. It was developed by Facebook to complement the strengths of the React view framework. In this course with Andrew Burgess, you’ll build a simple Twitter clone using the Flux architecture, with React powering the views.

7. Unit Testing React Components

React is a very popular library, so you can find courses all over the web that will teach you how to use its amazing features. However, sometimes testing isn’t talked about. React’s functional programming model actually makes it easy to unit test components. 

In this course, Envato Tuts+ instructor Andrew Burgess will teach you how to unit test your React components. You’ll see how to use Enzyme, the Airbnb unit-testing library, which builds on top of React’s own testing functionality.

Want More React?

We’ve got a course geared specifically towards taking your React skills as far as possible. In this course, you will get you started building modern web apps with React and Redux. Starting from nothing, you’ll use these two libraries to build a complete web application. 

You’ll start with the simplest possible architecture and slowly build up the app, feature by feature. You’ll learn about basic concepts like tooling, reducers, and routing. You’ll also learn about some more advanced techniques like smart and dumb components, pure components, and asynchronous actions. By the end, you’ll have created a complete flashcards app for learning by spaced repetition.

Interested? Check it out!

Start Learning With a Free Trial

You can take all of these React courses, and plenty more from our growing library, with a free 10-day trial of our monthly subscription. So get started today, and master this popular and powerful JavaScript library.

View Tutorial: 7 Popular React Courses for JavaScript Developers

Invisible Forces: Size, Contrast, and Balance

This is the second of a three-part series of articles about “invisible forces” in design. In the previous article, we learned about how alignment can be used to create direction and focus. In this article, we’ll learn about how working with size changes can create contrast and balance, and help your designs communicate more clearly.

Bigger Stuff Looks More Important

It’s obvious that when you make an element bigger, it tends to look more important than the smaller elements.

But, this needs to be considered along with other factors that affect visual hierarchy. For example, these two elements take on about the same level of importance, because they’re the same size:

If anything, you’d see the top element before you’d see the bottom element.

But if you make the bottom element bigger than the top element, it will look more important.

However, other things such as visual weight (are you using a bold or light font), or color contrast, can reverse the effects of larger size.

In this illustration, the lighter element looks less important, even though it’s bigger.

But just by giving the same illustration a dark background, now the lighter (and bigger) element is dominant, thanks to the fact that it contrasts the background more than the smaller element.

Make Meaningful Size Changes

Especially when designing for the tiny screens of today’s age, you should be using size changes with purpose. There’s no point in making a font larger–and thereby taking up valuable screen real-estate–if it’s not necessary.

Whenever possible, you can use the factors mentioned above to change your visual hierarchy, but sooner or later, you need to make one thing bigger than another. Just don’t do it haphazardly.

Look at these different elements, each one larger than the previous.

Now, which reads more clearly to you: that layout, or this one?

The elements from the second example are sized based upon a varied scale. Each font size relates to the next smallest size with the same mathematical relationship as it relates to the larger size.

The type sizes in the varied scale have a proportional relationship to one another. Proportions help make parts of your designs look like they belong together.

You can see proportions in action in the MailChimp logo.

Each of the circles that make up the features of the chimp relate to each other by a factor of .75. The circle that makes up the belly area is .75 the size of the circle that makes up the body, for example. Hicks Design, the firm that designed this logo, did this on purpose!

Don’t be Fooled by Fools’ Gold

Many of you are probably thinking about the so-called “Golden Ratio” that gets a lot of hype. The golden ratio is roughly 1:1.618. Yes, the chimp would still be attractive if it were based upon the golden ratio, but it wouldn’t be objectively any more attractive. Despite the hype, there is no evidence that The Golden Ratio is any more attractive than other popular ratios such as .75, or .67.

To illustrate this, I once polled my email list about which of the above rectangles they found more attractive. One of them is a square, another is a .75 rectangle, another is a .67 rectangle, and another is a “Golden” rectangle. Which rectangle looks most attractive to you?

Here are the poll results:

  • top left (Square): 8%
  • top right (3:4 rectangle): 29%
  • bottom left (2:3 rectangle): 37%
  • bottom right (“Golden” Ratio): 25%

As you can see, the so-called golden rectangle performed very well, but it didn’t turn out to be the most attractive rectangle.

The 2:3 rectangle won in this case, but don’t read too much into that. The point is, anything from the Golden Ratio to 3:4 is going to be more attractive than a square.

You can use this knowledge to make your typography beautiful, and save time if you work with a pre-set varied scale for your typography.

For example, these are the font sizes that I always use. Each size is roughly .75 the size of the previous size (with a little rounding).

A side-benefit of working with a .75 scale instead of the golden ratio, is the math is much easier to do in your head: What’s 75% of 16? Easy! What’s 61.8% of 16? Errr.

Conclusion

By thinking about the size changes you make, your designs will look cleaner and clearer, and while being more usable, and converting better. If you use a varied scale, you can actually make great designs faster!

Stick around for the final article in this series, where we’ll learn how shaping the page through alignment and sizing, and thinking about your white space, helps give your designs even more clarity.

View Tutorial: Invisible Forces: Size, Contrast, and Balance

How to Start a Telegram Bot With PHP

If you are reading this, you know that chat bots are one of the biggest tech trends of 2016.

The bot revolution is not only about artificial intelligence. A bot can be a tool in your messenger with a simple chat interface that can be used to extend the functionality of sites or services or can even be a standalone application. Bots are cheaper to develop and easier to install, and another great feature is that messengers can be used on every type of device—laptops, smartphones, and tablets. That’s why everybody is crazy about bots now.

And the biggest messenger with an open bot API is Telegram.

What We Are Going to Do

In this article we will create a simple stopwatch Telegram bot. I will show you how to create your bot, connect with analytics, write some code, and finally add your bot to a bot store.

By the way, I’ve already prepared a demo, so you can test it just by adding @stopwatchbot to your Telegram contact list.

Create a Bot With BotFather

The first step to creating a bot is to register the account of your bot in Telegram. And there is a bot for that, called the BotFather. Just add it to your contact list and you’ll be able to create and set up Telegram bots, just by typing the /newbot command and following the instructions of BotFather.

BotFather running Telegram

After registering your new bot, you will receive a congratulations message with an authorization token. We will use this token soon to authorize a bot and send requests to the Bot API.

Later you can use BotFather to add descriptions or photos to the profiles of your bots, regenerate tokens, set lists of commands to use, delete accounts, and so on. To get a full list of commands, just type /help in a chat to get a list of BotFather’s commands.

Connect to Botan Analytics

There is no built-in analytics in the Telegram Bots API, but it’s important to know how many users you have, how they act, and which commands they trigger more. Of course, we can collect this information using our own engine, but if we want to focus on bot functionality, not metrics, we just need to use an out-of-the-box solution.

And there is a simple tool to connect your bot to analytics, called Botan. It’s based on Yandex AppMetric and completely free. Using Botan, you can segment your audience, get information about user profiles, get the most used command, and get beautiful graphs right in your messenger, like this:

Bot Analytics Graph

To get started, you need to register your bot in Botan and get a token. And again, you can do it with a bot, BotanioBot:

Registering a bot in Telegram

Just click the “Add bot” key on the dialog keyboard, type the nick of your bot, and you will get your bot track token. Now Botanio is ready to track your bot events, and you can get statistics by users, sessions, retention and events right in your messenger.

Create and Register an SSL Webhook

In Telegram there are two ways to get messages from your users: long polling and webhooks.

A diagram of the Telegram API

Basically, with long polling, you need to request new messages from the API, and with webhooks you are setting a callback that the Telegram API will call if a new message arrives from a user. I prefer to use webhooks because it looks like real-time communication, so in this article we will use this method too. Now we need to choose a callback URL for our webhook, which needs to be reached under the HTTPS protocol, and we need to set it really secure, so hide your script in a secret path, as the manual says:

If
you’d like to make sure that the Webhook request comes from Telegram,
we recommend using a secret path in the URL,
e.g. https://www.example.com/<token>.
Since nobody else knows your bot‘s token, you can be pretty sure
it’s us.

If your SSL certificate is trusted, all you need to do is open this URL in your browser:

https://api.telegram.org:443/bot[token]/setwebhook?url=[webhook]

Otherwise you have to generate a self-signed certificate. Here is an example of the command on Linux for it:

openssl req -newkey rsa:2048 -sha256 -nodes -keyout /path/to/certificate.key -x509 -days 365  -out /path/to/certificate.crt -subj "/C=IT/ST=state/L=location/O=description/CN=yourdomain.com"

And don’t forget to open the SSL port:

sudo ufw allow 443/tcp

To get the certificate checked and set your webhook domain to trusted, you need to upload your public key certificate:

curl \
  -F "url=https://yourdomain.com/path/to/script.php" \
  -F "certificate=/path/to/certificate.key" \
  "https://api.telegram.org/bot[token]/setwebhook"

Finally you will get a JSON reply like this:

{"ok":true,"result":true,"description":"Webhook was set"}

It says that the webhook was set and we are ready to start the engine of the bot.

Build a Database

Now we need to build a database for our timers. What do we need to store in it? When a user commands the stopwatch to start, we will take the ID of the chat and save a row with the chat ID and current Unix time, which is the number of seconds between now and the start of Unix Epoch, which is 1 January 1970 at UTC. Consequently, we will save a row with the chat ID and integer timestamp of the current Unix time.

To show the current stopwatch time, we will get the saved timestamp and compare it with the current timestamp. The difference will be the current time in seconds. If the user stops the timer, we will simply delete the row with the current chat ID.

So let’s create a database and table to store the stopwatch information:

CREATE TABLE IF NOT EXISTS `stopwatch` (
  `chat_id` int(10) unsigned NOT NULL,
  `timestamp` int(10) unsigned NOT NULL,
  PRIMARY KEY (`chat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Create a Stopwatch Class

Finally we are ready to start coding. Let’s create a class to work with the database in a file called stopwatch.php and start with a constructor that will set two private variables, where we will store the chat ID and the current MySQL connection:

class Stopwatch
{
    /** @var mysqli */
    private $mysqli;
    /** @var int */
    private $stopwatch_id;
    /**
     * Stopwatch constructor
     * @param mysqli $mysqli
     * @param $stopwatch_id
     */
    public function __construct(\mysqli $mysqli, $stopwatch_id)
    {
        $this->mysqli = $mysqli;
        $this->stopwatch_id = intval($stopwatch_id);
    }
}

When the user starts the timer, we will get the current Unix time and save it in a row with the chat ID, so here is the start() method:

public function start()
{
    $timestamp = time();
    $query = "
        INSERT INTO  `stopwatch` (`chat_id`, `timestamp`)
        VALUES ('$this->stopwatch_id', '$timestamp')
        ON DUPLICATE KEY UPDATE timestamp = '$timestamp'        
    ";
    return $this->mysqli->query($query);
}

If the timer stops, we need to delete a row from the database:

/**
 * Delete row with stopwatch id
 * @return bool|mysqli_result
 */
public function stop()
{
$query = "
    DELETE FROM `stopwatch`
    WHERE `chat_id` = $this->stopwatch_id
    ";
    return $this->mysqli->query($query);
}

And now for the main part of the class. When the user requests the status of the timer, we need to find the row with the stopwatch from the current conversation and calculate the difference in seconds between the saved Unix time and the current time. Fortunately, Unix time is an integer, so we can just subtract one value from another. To format the resulting value as a time, we will use the gmdate function.

/**
 * Find row with stopwatch id and return difference in seconds from saved Unix time and current time
 * @return string
 */
public function status()
{
    $query = "
        SELECT `timestamp` FROM  `stopwatch`
        WHERE `chat_id` = $this->stopwatch_id        
    ";
    $timestamp = $this->mysqli->query($query)->fetch_row();
    if (!empty($timestamp)) {
        return gmdate("H:i:s", time() - reset($timestamp));
    }
}

As you can see, if there is no value in the database, the method status() will return nothing, and we will process a null value like a stopped timer.

Choosing a PHP Library

There are many PHP libraries that exist to work with the Telegram API, but, at least at the moment of writing this article, there’s only one that supports both the Telegram Bot API wrapper and Botan tracking. And it’s called PHP Telegram Bot API.

Use Composer to install this library:

composer require telegram-bot/api

If you’re not interested in using analytics, try Telegram Bot API PHP SDK with Lavarel integration or PHP Telegram Bot.

Start the Webhook Script

And now the main part begins—we will create a script to process callbacks from the Telegram Bot API. Start a file called index.php and include Composer autoload and a new Stopwatch class. Open a MySQL connection, create a new Telegram API client, and run it:

require_once 'vendor/autoload.php';
require_once 'stopwatch.php';

// connect to database
$mysqli = new mysqli('database_host', 'database_user', 'database_password', 'database_name');
if (!empty($mysqli->connect_errno)) {
    throw new \Exception($mysqli->connect_error, $mysqli->connect_errno);
}

// create a bot
$bot = new \TelegramBot\Api\Client('bot_token', 'botanio_token');
// run, bot, run!
$bot->run();

Create Commands

Now we need to set up a bot to answer on command /start. This command is used to start all Telegram bots, and users will be shown our welcome message when the first chat begins.

$bot->command('start', function ($message) use ($bot) {
    $answer = 'Howdy! Welcome to the stopwatch. Use bot commands or keyboard to control your time.';
    $bot->sendMessage($message->getChat()->getId(), $answer);
});

Here, in the command() method, we defined a closure for receiving a command. This closure gets the ID of the current chat and sends a welcome message. Also, all registered commands are automatically tracked as the command name.

To start the stopwatch, we will define the /go command:

$bot->command('go', function ($message) use ($bot, $mysqli) {
    $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
    $stopwatch->start();
    $bot->sendMessage($message->getChat()->getId(), 'Stopwatch started. Go!');
});

This will create an instance of the Stopwatch class and start a timer calling the start() method that we have defined already.

To define the /status command, we need to do the same thing. Just call the status() method and return the result. If the method returned null, tell the user that the timer is not started.

$bot->command('status', function ($message) use ($bot, $mysqli) {
    $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
    $answer = $stopwatch->status();
    if (empty($answer)) {
        $answer = 'Timer is not started.';
    }
    $bot->sendMessage($message->getChat()->getId(), $answer);
});

And if the user stops the timer, we need to get the status first, show the resulting time, and stop the timer using the stop() method.

$bot->command('stop', function ($message) use ($bot, $mysqli) {
    $stopwatch = new Stopwatch($mysqli, $message->getChat()->getId());
    $answer = $stopwatch->status();
    if (!empty($answer)) {
        $answer = 'Your time is ' . $answer . PHP_EOL;
    }
    $stopwatch->stop();
    $bot->sendMessage($message->getChat()->getId(), $answer . 'Stopwatch stopped. Enjoy your time!');
});

That’s it! Now you can upload all the files to the webhook directory and test your bot.

Adding a Keyboard

To suggest to the user which commands he or she can run, we can add a keyboard to a message. Our stopwatch can be running or stopped, and there will be two ones for each state. To show a keyboard to the user, we just need to extend the sendMessage() method:

$keyboard = new \TelegramBot\Api\Types\ReplyKeyboardMarkup([['/go', '/status']], null, true);

$bot->sendMessage($message->getChat()->getId(), $answer, false, null, null, $keyboards);
});

Now you can add keyboards to every command of your bot. I will not include a full example here, but you can see it in the repository pages.

Adding Your Bot to a Store

Okay, so now we have working bot, and we want to show it to the world. The best way is to register the bot in a bot catalogue. For now, Telegram doesn’t have an official catalogue like this, but there are a few unofficial ones, and the biggest is Storebot.me, where thousands of bots are already registered.

And there is a… bot to register your bot in a bot store! Add @storebot to your contact list, type the /add command, and follow the instructions. You will be asked to enter the bot’s username, name, and description, choose one of the standard categories, and confirm the bot’s ownership by sending its token.

After a while, your bot will pass the submission process and appear in the Storebot charts. Now you and your users can vote, find and rate your bot in the bot store to help it rise to the top of the chart.

Conclusion

We’ve come a long way, from creating a baby bot to registering it in a store to be available to real users. As you can see, there are many tools that exist to make your life easier with creating and spreading your bot, and you don’t need much code to start an easy bot. Now you are ready to make your own!

If you have any questions, don’t hesitate to ask questions in the comments to the article. 

Further Reading and Related Links

View Tutorial: How to Start a Telegram Bot With PHP

How to Create a Stripes and Flowers Pattern From Scratch in Adobe Illustrator

What You’ll Be CreatingRoses and flowers can be a daunting task without photographic reference. Take the guesswork out of designing beautiful floral patterns in Adobe Illustrator with this seamless pattern tutorial! Together we’ll create flowers, a uni…

View Tutorial: How to Create a Stripes and Flowers Pattern From Scratch in Adobe Illustrator