I wrote some Rspec tests for our recent release of the state_machine_audits gem, and thought I'd share the steps I took to add Rspec tests. To get started, I had to get the code and update the gemspec.
Setting up the .gemspec
The git repository containing the source code can be found on Github or by clicking the "Source Code" link on RubyGems.org. I used the command
git clone git://github.com/isotope11/state_machine_audits.git
to clone the repository into a folder called state_machine_audits in
the present working directory. Before I could start adding Rspec tests, I had to
add rspec and sqlite3 to the development dependencies under
Gem::Specification.
# in state_machine_audits.gemspec
Gem::Specification.new do |s|
# ...
s.add_development_dependency 'rspec', '~> 2.4.0'
s.add_development_dependency 'sqlite3', '~> 1.3.3'
end
Adding Rspec tests
After installing the rspec gem and requiring the libraries used by state_machine_audits, I used ActiveRecord to create a sqlite3 database in memory and ran migrations against that database:
# in spec/state_machine_audits_spec.rb
require 'active_record'
require 'active_support'
require 'state_machine'
require 'state_machine_audits'
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Base.connection.create_table(:state_machine_state_audits) do |t|
t.string :state_machine_auditable_type
t.integer :state_machine_auditable_id
t.string :state_field
t.string :state
t.timestamps
end
Next, I added a generic Vehicle model with migrations and an ignite event to use the state_machine gem:
# in spec/state_machine_audits_spec.rb
class Vehicle < ActiveRecord::Base
include StateMachineAudits
state_machine :initial => :parked do
event :ignite do
transition :parked => :first_gear
end
end
end
Finally, I used the Rspec
describe syntax to test that audits were being added to the database after state changes. To run the tests, I used
bundle exec rspec spec/ to make sure the tests were run against the version specified in the gemspec. The only thing left was to update the version and push the changes to RubyGems.
Changing versions and pushing changes
Updating the version was simple -- I just modified the file lib/state_machine_audits/version.rb. After Josh added my RubyGems account to the permissions, I used the command gem build in the gem's root directory to generate a new gem file, and gem push state_machine_audits-0.1.1.gem to update the RubyGems version. That's it! Oh, and if you are contributing to gem development, don't forget to add yourself to the authors before you push ;)