Ensure that you have the following gem in your Gemfile:
group :development, :test do gem 'rspec-rails' gem 'spork' gem 'faker' end
In our Rails application, to set up RSpec we need to invoke the following command:
$ rails generate rspec:install
create .rspec
create spec
create spec/spec_helper.rb
Removing specific ActiveRecord configuration.
You will need to comment the following lines in the spec/spec_helper.rb
file to ensure there aren't any errors due to ActiveRecord:
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
Now, we can write some RSpec code on our own. We can write the Author
model test specifications in spec/models/author_spec.rb:
require 'spec_helper' describe Author do it "should be created if name is provided" do Author.create(name: "test").should be_valid end it "should not be created without a name" do Author.create.should_not be_valid end end
To see if the test cases pass, we can run RSpec, as follows:
$ rspec spec/models
..
Finished in 5.08 seconds
2 examples, 0 failures
Depending on the machine, the Ruby version, the Rails version, and the RSpec version, the speed of the tests may vary.
Let's look at what we tested! But first, let's look at some basics of RSpec:
describe:
This is a method (yes, a method) that takes a string and a block of code which has all the test cases in it.it:
This is another method that takes a string as the name of the test case and a block of code for the actual test case.should:
This is a method that does the actual validation of the test case. If this method returns true
, the test case passes, otherwise it fails.should_not:
This is the inverse of the should
method.be_valid:
This is a method which validates an object's existence.There are plenty of other methods that you can read up in the RSpec book! Let's look at one test case! Have a look at the following code snippet:
it "should be created if name is provided" do
Author.create(name: "test").should be_valid
end
Here, we create an author and test if it "should be valid". If the object is successfully created, it will not be nil or in other words, it will be valid!
Notice that running two tests took about five seconds! Welcome spork— a speedy way to get RSpec up and running.
18.219.141.208