开发者

Rails/Rspec Stubs: Specifying order & so forth

开发者 https://www.devze.com 2023-03-08 15:37 出处:网络
I\'m comfortable creating basic stubs, but a little confused about how to specify things such as order (a开发者_如何学编程nd reversing it), etc.

I'm comfortable creating basic stubs, but a little confused about how to specify things such as order (a开发者_如何学编程nd reversing it), etc.

To give a concrete example, here is a line in my controller that I'm trying to test:

@courses = Course.order('created_at').reverse

In my controller spec, the (obviously failing) stub is:

  Course.stub(:all) { [mock_course] }

...and the rspec error:

  Failure/Error: assigns(:courses).should eq([mock_course])

       expected [#<Course:0x818614e8 @name="Course_1001">]
            got [#<Course id: 2, name: "Second test course", price: #<BigDecimal:1030e73c0,'0.4995E2',18(18)>]

Despite being an inaccurate test (not testing ordering), i would have guessed the spec would pass. It doesn't - it's pulling from the database, not the mock. Soo...I guess what I'm asking is, how do I stub Course.order('created_at').reverse ?

Many thanks...


You're assuming that ActiveRecord will call Course.all at some point, which may not be the case.

Try this:

Course.stub_chain(:order, :reverse) { [mock_course] }

To avoid having to do chained stubbing, you could move the ActiveRecord code into your model, so the controller would have something simpler such as:

Course.all_by_newest_first
0

精彩评论

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