rspec(5) - mock
2028 ワード
テストされていないコードはごろつきです rspec(1) - summary specs(2) - model specs(3) - controller specs(4) - request specs(5) - mock [specs(6) - mailer] [specs(7) - view] [specs(8) - routing] [specs(9) - helper] [specs(10) - factory-girl] [specs(11) - fake other gems] [specs(12) - sidekiq] [specs(13) - db migration] [specs(14) - timecop] [specs(15) - jenkins]
here we talk about rspec-mock before we start to test our code, we need to prepare our sample data, it is so bored to create many objects repeatly in our test cases. of course, we write helper methods to save time. but this method is not flexible enough. because sometimes we want to change our object attributes we hope there is a method which provide a with any attributes and method accessible, and it is so opened that we can change it easily. yes, what you are looking for is
now, you got a user object. assume it has
it looks like a OpenStruct.
we can stub a method to an existed object.
stub multiple methods to a existed object
here we talk about rspec-mock before we start to test our code, we need to prepare our sample data, it is so bored to create many objects repeatly in our test cases. of course, we write helper methods to save time. but this method is not flexible enough. because sometimes we want to change our object attributes we hope there is a method which provide a with any attributes and method accessible, and it is so opened that we can change it easily. yes, what you are looking for is
mock
- rspec-mock it provides so many useful features. let's talk about it. object
user = double('user')
now, you got a user object. assume it has
name
and 'sex` user = double(:user, name: 'zql', sex: 'male')
# we access user's attributes
user.name.should eq 'zql'
v.sex.should eq 'male'
it looks like a OpenStruct.
stub methods
we can stub a method to an existed object.
user = double()
allow(user).to receive(:email) { "[email protected]" }
expect(user.email).to be"[email protected]"
stub multiple methods to a existed object
user = double()
allow(user).to receive_messages(:foo => 2, :bar => 3)
expect(user.foo).to eq 2
expect(user.bar).to eq 3
test method call
user = double()
expect(user).to receive(:foo)