开发者

RSpec -- lambda usage

Can someone please explain the difference between the following methods to me?

it "should create a user" do
    lambda do
        post :create, :user => @attr
    end.should change(User, :count).by(1)
end

That is the method as it currently stands开发者_StackOverflow. Could this also be achieved with the method below?

it "should create a user" do
    post :create, :user => @attr
    response.should change(User, :count).by(1)
end

Are these effectively the same? Or does the second not work? Because the tutorial I'm following seems to use response whenever possible, yet did not do it in the above case. Can someone please explain the difference between the two above methods, how lambda and RSpec's response work? Thanks!


The lambda form is equivalent to doing this, if the test database is empty:

User.count.should == 0
post :create, :user => @attr
User.count.should == 1

I believe that calling change without supplying a block, as you show in the second example, will generate an error.

The lambda form is used to wrap a section of code which can be used for setting an expectation in a more convenient way then testing with before and after conditions. In more recent versions of RSpec you'll also see this done with expect:

expect {
  post :create, :user => @attr
}.to change(User, :count).by(1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜