Rspec

21
RSpec documentation http://relishapp.com/rspec

description

 

Transcript of Rspec

Page 1: Rspec

RSpecdocumentation

http://relishapp.com/rspec

Page 2: Rspec

componentsRSpec Core

RSpec Expectations

RSpec Mocks

RSpec Rails

Page 3: Rspec

run specsrake specrake spec:modelsrspec spec/models/order_spec.rbrspec spec/models/order_spec.rb:19

Page 4: Rspec

"be" matchersdescribe 0 do it { subject.zero?.should == true } # vs. it { should be_zero } # 0.zero? == trueend

Page 5: Rspec

have(n).items matchercollection.should have(x).itemscollection.should have_at_least(x).itemscollection.should have_at_most(x).itemsit { should have(5).line_items }

Page 6: Rspec

subject

Page 7: Rspec

implicit subjectdescribe Comment do subject { Comment.new }end

Page 8: Rspec

explicit subjectdescribe Order do subject { Factory.build(:order) }end

Page 9: Rspec

implicit receiverit { subject.should be_valid }# vs.

it { should be_valid }

Page 10: Rspec

itsits(:status_name) { should == :draft }its('line_items.count') { should == 5 }

Page 11: Rspec

letbefore do @order = Factory.create(:shipped_order)end# vs.

let(:order) do Factory.create(:shipped_order)end

Page 12: Rspec

context vs. describealias :context :describe

describe is for methods

context is for contexts

Page 13: Rspec

class & instance methodsdescribe '#title' do # instance method ...enddescribe '.title' do # class method ...end

Page 14: Rspec

contextcontext 'when quantity is negative' do before { subject.quantity = -1 } ...end

Page 15: Rspec

model validationsit { should be_invalid }its(:errors) { should be_present }it { should have(1).errors_on(:quantity) }

Page 16: Rspec

shoulda-matchersit 'should validate email and quantity' do subject.email = '[email protected]' subject.quantity = -1 subject.valid? should have(:no).errors_on(:email) should have_at_least(1).error_on(:quantity)end# vs.

it { should allow_value('[email protected]').for(:email) }it { should_not allow_value(-1).for(:quantity) }

Page 17: Rspec

mocksfake objects and methods

don't touch database

faster specs

Page 18: Rspec

rails model mocksmock_model is a test double that acts like an

ActiveModel

stub_model is a instance of a realActiveModel with some methods stubbed

Page 19: Rspec

using mockslet(:email_template) do stub_model(EmailTemplate, :name => 'test_email', ...)endbefore do ... EmailTemplate.stub(:find_by_name). with('test_email'). and_return(email_template)end

Page 20: Rspec

message expectationdef should_deliver_mail(method) Mailer.should_receive(method). with(subject). and_return(double(:deliver => nil))end

Page 21: Rspec

questions?