Tuesday, July 22, 2008

ordered method testing with rspec

Since I am learning RSpec for Rails I wonder how to write a test which tests the order of the methods called by my method. Now I found a solution which works. The answer is simple: should_receive takes a block which is called after the assertion of the should_receive ran.

Your code may look like this:

    1 # user.rb
2 def change_my_attributes(name,login,password)
3 self.name = name
4 self.login = login
5 self.password = password
6 save!
7 end
8
9 # user_spec.rb
10 it "should run my methods in #change_my_attributes in the correct order" do
11 @user = User.new
12 @user.should_receive(:name=) do
13 @user.should_receive(:login=) do
14 @user.should_receive(:password=) do
15 @user.should_receive(:save!)
16 end
17 end
18 end
19 @user.change_my_attributes('foo','bar','foobar')
20 end


Looks kind of ugly but it works...

2 comments:

Thorsten Böttger said...

Absolutely, ugly, but as long as it works ;-)

Benjamin Behr said...

Perhaps it's time to write a matcher... :)