Skip to content

Instantly share code, notes, and snippets.

@zishe
Last active August 29, 2015 14:13
Show Gist options
  • Save zishe/5aff6c83a3dd1e30c99f to your computer and use it in GitHub Desktop.
Save zishe/5aff6c83a3dd1e30c99f to your computer and use it in GitHub Desktop.
Testing State Machine scopes
describe "scopes" do
# this doesn't work for state machine
# it "has scope :repaid" do
# AccountTransaction.should respond_to(:repaid)
# AccountTransaction.repaid.where_values_hash.should == { :state => :repaid }
# end
# The easiest solution
before(:all) do
%i(new pending posted cancelled repaid failed).each { |state| FactoryGirl.create(:account_transaction, state: state) }
end
it "has scope repaid" do
AccountTransaction.repaid.pluck(:state).should == %w(repaid)
end
it "has scope active" do
AccountTransaction.active.pluck(:state).should == %w(new pending posted)
end
# Using where_clauses
it "has scope repaid" do
where = AccountTransaction.repaid.arel.where_clauses
where.should include "(\"account_transactions\".\"state\" IN ('repaid'))"
end
end
# Shared Example:
module ModelHelpers
RSpec.shared_examples "scoped state machine" do |model, scope_name, states|
let(:scoped) { model.send(scope_name).arel.where_clauses }
let(:table) { model.to_s.underscore.pluralize.to_sym }
it "has scope #{scope_name} with states [#{[states].flatten.join ' '}]" do
scoped.should include "(\"#{table}\".\"state\" IN ('#{[states].flatten.join "','"}'))"
end
end
end
# usage:
it_behaves_like "scoped state machine", AccountTransaction, :repaid, 'repaid'
it_behaves_like "scoped state machine", AccountTransaction, :active, %w(new pending posted)
# Not sure about `[states].flatten` 2 times, I'll be glad to any suggestions about this topic.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment