Last active
August 29, 2015 13:55
-
-
Save shannonwells/56fd5692f8a0deee7927 to your computer and use it in GitHub Desktop.
My favorite rspec snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sanity tests for factories and persistence in db | |
# Makes sure you have not inadvertently hosed validation, and suchlike when models are changed | |
shared_examples_for 'a model' do |factory, factory_params = {}| | |
let(:model) { FactoryGirl.build(factory, factory_params) } | |
it 'can be persisted' do | |
expect(model).to be_valid | |
model.save! | |
expect(model).to be_persisted | |
end | |
context 'row can be found' do | |
before do | |
model.save unless model.persisted? | |
end | |
subject{described_class.first} # described_class will be valid when this module is included. | |
it { | |
should be_a described_class | |
} | |
end | |
end | |
# Controller shared example! | |
shared_examples_for 'an action where login is required' do |verb,action| | |
subject { | |
# self is controller. may need to set type: :controller inside main RSpec block | |
self.send(verb, action) | |
response | |
} | |
it { should be_redirect } | |
it { should redirect_to '/users/sign_in' } | |
end | |
# Example of how you can DRY up your specs when you do a bunch of the same test, | |
# where you don't want or need to make shared examples: | |
context 'any other state' do | |
subject { get :show, format: :json } | |
let(:myobject) { FactoryGirl.create(:myobject, :sometrait) } | |
['some_error','some_other_error'].each do |state| | |
before do | |
myobject.update_attributes(approval_state: state) | |
end | |
it { should be_success } | |
# You can interpolate within a test example title | |
it "displays error template (#{state})" do | |
subject | |
results = JSON.parse response.body | |
expect(results['display_template']).to eql 'error' | |
end | |
end | |
end | |
# RR mocks and stubs | |
# If you need to do a mock/stub chain, "anything" must be provided for each parameter required. | |
any_instance_of(MyPostingRequestClass) do |klass| | |
mock(klass).post_request(anything,anything,anything,anything) { response } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment