ruby on rails - Rspec and testing instance methods -
here rspec
file:
require 'spec_helper' describe classroom, focus: true describe "associations" { should belong_to(:user) } end describe "validations" { should validate_presence_of(:user) } end describe "instance methods" describe "archive!" before(:each) @classroom = build_stubbed(:classroom) end context "when classroom active" "should mark classroom inactive" @classroom.archive! @classroom.active.should_be == false end end end end end
here classroom factory
:
factorygirl.define factory :classroom name "hello world" active true trait :archive active false end end end
when instance method test runs above, receive following error: stubbed models not allowed access database
i understand why happening (but lack of test knowledge/being newb testing) can't figure out how stub out model doesn't hit database
working rspec tests:
require 'spec_helper' describe classroom, focus: true let(:classroom) { build(:classroom) } describe "associations" { should belong_to(:user) } end describe "validations" { should validate_presence_of(:user) } end describe "instance methods" describe "archive!" context "when classroom active" "should mark classroom inactive" classroom.archive! classroom.active == false end end end end end
your archive!
method trying save model database. , since created stubbed model, doesn't know how this. have 2 possible solutions this:
- change method
archive
, don't save database, , call method in spec instead. - don't use stubbed model in test.
thoughtbot provides example of stubbing dependencies here. subject under test (orderprocessor
) bona fide object, while items passed through stubbed efficiency.
Comments
Post a Comment