From samwgoldman at gmail.com Tue Nov 1 10:34:02 2011 From: samwgoldman at gmail.com (Sam Goldman) Date: Tue, 1 Nov 2011 10:34:02 -0400 Subject: [rspec-users] API for defining top-level DSL methods? Message-ID: I am in the process of writing a simple DSL inside of rspec, which defines some methods that wrap describe/example and augment the metadata, like capybara's "feature/scenario" methods. From the excellent RSpec book, I know how to use Configuration to extend RSpec in a forward-compatible way, but it is unclear to me how to define methods on the very top-level, so I could write specs like this: require 'my_class' describify 'something funky' do; ...; end I looked into how capybara is doing it, and I see that when one includes 'capybara/rspec' that causes a class-level method to be defined in the "global" scope[1]. Is this the preferred way of defining such a method for use in RSpec DSLs, or is there a better way? I have been able to use this method successfully. Thanks, Sam 1. https://github.com/jnicklas/capybara/blob/f41018f884c53633b6744d26ed1d21fb08e3b92f/lib/capybara/rspec/features.rb -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Tue Nov 1 11:19:07 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 1 Nov 2011 10:19:07 -0500 Subject: [rspec-users] API for defining top-level DSL methods? In-Reply-To: References: Message-ID: <4202AC90-374C-4BFC-B540-8F87C08D657A@gmail.com> On Nov 1, 2011, at 9:34 AM, Sam Goldman wrote: > I am in the process of writing a simple DSL inside of rspec, which defines some methods that wrap describe/example and augment the metadata, like capybara's "feature/scenario" methods. From the excellent RSpec book, I know how to use Configuration to extend RSpec in a forward-compatible way, but it is unclear to me how to define methods on the very top-level, so I could write specs like this: > > require 'my_class' > describify 'something funky' do; ...; end > > I looked into how capybara is doing it, and I see that when one includes 'capybara/rspec' that causes a class-level method to be defined in the "global" scope[1]. Is this the preferred way of defining such a method for use in RSpec DSLs, or is there a better way? I have been able to use this method successfully. > > Thanks, > Sam > > 1. https://github.com/jnicklas/capybara/blob/f41018f884c53633b6744d26ed1d21fb08e3b92f/lib/capybara/rspec/features.rb We don't have a formal API, but we should: https://github.com/rspec/rspec-core/issues/493 In the mean time, just use alias. Cheers, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From patrick at collinatorstudios.com Wed Nov 2 22:46:12 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Wed, 2 Nov 2011 19:46:12 -0700 (PDT) Subject: [rspec-users] view_context in specs Message-ID: I have a presenter class which is instantiated like this: class Blah def initialize(context) @context = context end def do_something_view_related @context.render :partial => "/...somewhere" end def do_something_else_view_related @context.content_tag :p, "fancy paragraph" end end class BlahController < ApplicationController def blah @blah = Blah.new(view_context) end end ... I've gotten around this in my specs by doing something like: describe Blah do it "is blaherrific" do context = stub(:render => "some content...", :link_to => "somewhere) blah = Blah.new(context) blah.do_someting_view_related.should == "some content..." end end But I would much rather actually be able to call upon the real view context in my specs so that my tests are more realistic. Is the best way to get a real-world view context in there to do something like: Blah.new(ActionView::Base.new) ? Or does RSpec have something magical already setup for this sort of thing? Muchas Gracias. Patrick J. Collins http://collinatorstudios.com From dchelimsky at gmail.com Wed Nov 2 22:52:30 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 2 Nov 2011 21:52:30 -0500 Subject: [rspec-users] view_context in specs In-Reply-To: References: Message-ID: <6A85E60E-06A1-43BB-B07D-FEF7658E03A8@gmail.com> On Nov 2, 2011, at 9:46 PM, Patrick J. Collins wrote: > I have a presenter class which is instantiated like this: > > class Blah > > def initialize(context) > @context = context > end > > def do_something_view_related > @context.render :partial => "/...somewhere" > end > > def do_something_else_view_related > @context.content_tag :p, "fancy paragraph" > end > > end > > class BlahController < ApplicationController > > def blah > @blah = Blah.new(view_context) > end > > end > > ... > > I've gotten around this in my specs by doing something like: > > describe Blah do > > it "is blaherrific" do > context = stub(:render => "some content...", :link_to => " href="www.somewhere.com">somewhere) > blah = Blah.new(context) > > blah.do_someting_view_related.should == "some content..." > end > > end > > But I would much rather actually be able to call upon the real view context in > my specs so that my tests are more realistic. > > Is the best way to get a real-world view context in there to do something like: > > Blah.new(ActionView::Base.new) ? > > Or does RSpec have something magical already setup for this sort of thing? Nope. rspec-rails doesn't know that you want to write presenters :) I'd say just go w/ the real deal. HTH, David From dchelimsky at gmail.com Wed Nov 2 22:53:55 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 2 Nov 2011 21:53:55 -0500 Subject: [rspec-users] view_context in specs In-Reply-To: <6A85E60E-06A1-43BB-B07D-FEF7658E03A8@gmail.com> References: <6A85E60E-06A1-43BB-B07D-FEF7658E03A8@gmail.com> Message-ID: <9F39E2B9-06F6-4000-9004-E732D1453C3E@gmail.com> On Nov 2, 2011, at 9:52 PM, David Chelimsky wrote: > On Nov 2, 2011, at 9:46 PM, Patrick J. Collins wrote: > >> I have a presenter class which is instantiated like this: >> >> class Blah >> >> def initialize(context) >> @context = context >> end >> >> def do_something_view_related >> @context.render :partial => "/...somewhere" >> end >> >> def do_something_else_view_related >> @context.content_tag :p, "fancy paragraph" >> end >> >> end >> >> class BlahController < ApplicationController >> >> def blah >> @blah = Blah.new(view_context) >> end >> >> end >> >> ... >> >> I've gotten around this in my specs by doing something like: >> >> describe Blah do >> >> it "is blaherrific" do >> context = stub(:render => "some content...", :link_to => "> href="www.somewhere.com">somewhere) >> blah = Blah.new(context) >> >> blah.do_someting_view_related.should == "some content..." >> end >> >> end >> >> But I would much rather actually be able to call upon the real view context in >> my specs so that my tests are more realistic. >> >> Is the best way to get a real-world view context in there to do something like: >> >> Blah.new(ActionView::Base.new) ? >> >> Or does RSpec have something magical already setup for this sort of thing? > > Nope. rspec-rails doesn't know that you want to write presenters :) > > I'd say just go w/ the real deal. I should qualify that: I'd say just _start_ with the real deal. If it turns out painful, then look for alternatives. From patrick at collinatorstudios.com Wed Nov 2 23:29:13 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Wed, 2 Nov 2011 20:29:13 -0700 (PDT) Subject: [rspec-users] view_context in specs In-Reply-To: <6A85E60E-06A1-43BB-B07D-FEF7658E03A8@gmail.com> References: <6A85E60E-06A1-43BB-B07D-FEF7658E03A8@gmail.com> Message-ID: > > Is the best way to get a real-world view context in there to do something like: > > > > Blah.new(ActionView::Base.new) ? > > > > Or does RSpec have something magical already setup for this sort of thing? > > Nope. rspec-rails doesn't know that you want to write presenters :) > > I'd say just go w/ the real deal. Ok cool, thanks. It turns out ActionView::Base.new is a bit of a pain to try to use in this case since it lacks configuration of view paths and such. So what appears to be the simplest way to get this functionality is to do: @context = ActionController::Base.new.view_context then you can do @context.render, @context.content_tag, etc. Patrick J. Collins http://collinatorstudios.com From patrick at collinatorstudios.com Thu Nov 3 18:36:59 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Thu, 3 Nov 2011 15:36:59 -0700 (PDT) Subject: [rspec-users] problems matching generated html output... Message-ID: So, I am writing tests for a presenter class that outputs html markup. I have a method that does something like this: def output things.map do |thing| content_tag :div, :id => thing[:id] do [content_tag :p, thing[:body_1], content_tag :p, thing[:body_2].join.html_safe end end.join.html_safe end ... Then my spec is something like this: it "returns markup" do @presenter.stubs(:things).returns({:id => "an_id", :body_1 => "hello", :body_2 => "goodbye"}) @presenter.output.should == filter_for_html("

hello

goodbye

") end and I made this filter_for_html helper method which allows me to not care about whitespace... So that just does: def filter_for_html(markup) markup.squeeze(" ").strip.gsub(/\n\s+/, "") end And this effctively strips out all the whitespace and gives me a string like: "

hello

goodbye

" ... -- END OF BACKGROUND EXPLANATION -- Now for my question--- I have two problems and am not sure what the best to solve either one is: 1) The match fails because content_tag apparently inserts in a few \n's here and there. 2) My background explanation was actually quite simplified, and my presenter class is actually rendering some haml partials, and something like %ul.foo turns into
    (note the SINGLE QUOTES).. So my test fails because my expectation code uses double classes 3) Some of the text generated via the partials is calling things like .humanize which capitalize text and I am not really concerned about those details in my test.......... So the way I got my test passing is to do: @presenter.output.gsub("\n", "").gsub("'", "\"").downcase.should == filter_for_html(' ... same content as before ... ') Which I don't know about you, but that makes me go "ewwwwwwwwww". And makes all the RSpec readibility go out the window. Is there something I should be doing with a custom matcher or something to test for case-indifferent text, ignore whitespace and \n, and be quote indifferent? Thanks. Patrick J. Collins http://collinatorstudios.com From patrick at collinatorstudios.com Thu Nov 3 19:07:03 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Thu, 3 Nov 2011 16:07:03 -0700 (PDT) Subject: [rspec-users] problems matching generated html output... In-Reply-To: References: Message-ID: > So, I am writing tests for a presenter class that outputs html markup. > Actually now that I am thinking about it.. Would you guys recommend that I use something like Nokogiri to parse the content and test for things like number of children, classes, ids, etc, rather than just comparing the raw HTML? Patrick J. Collins http://collinatorstudios.com From matt at mattwynne.net Thu Nov 3 19:07:19 2011 From: matt at mattwynne.net (Matt Wynne) Date: Thu, 3 Nov 2011 23:07:19 +0000 Subject: [rspec-users] problems matching generated html output... In-Reply-To: References: Message-ID: <1E3AE5CF-5D6A-4F1D-B41C-F1762C5DBC94@mattwynne.net> On 3 Nov 2011, at 22:36, Patrick J. Collins wrote: > So, I am writing tests for a presenter class that outputs html markup. > > I have a method that does something like this: > > def output > > things.map do |thing| > > content_tag :div, :id => thing[:id] do > [content_tag :p, thing[:body_1], > content_tag :p, thing[:body_2].join.html_safe > end > > end.join.html_safe > > end > > ... > > Then my spec is something like this: > > it "returns markup" do > > @presenter.stubs(:things).returns({:id => "an_id", :body_1 => "hello", > :body_2 => "goodbye"}) > > @presenter.output.should == filter_for_html(" > >
    >

    hello

    >

    goodbye

    >
    > ") > end > > and I made this filter_for_html helper method which allows me to not care about > whitespace... So that just does: > > def filter_for_html(markup) > markup.squeeze(" ").strip.gsub(/\n\s+/, "") > end > > And this effctively strips out all the whitespace and gives me a string like: > "

    hello

    goodbye

    " > > ... > > -- END OF BACKGROUND EXPLANATION -- > > Now for my question--- I have two problems and am not sure what the best to > solve either one is: > > 1) The match fails because content_tag apparently inserts in a few \n's here > and there. > > 2) My background explanation was actually quite simplified, and my presenter > class is actually rendering some haml partials, and something like %ul.foo > turns into
      (note the SINGLE QUOTES).. So my test fails > because my expectation code uses double classes > > 3) Some of the text generated via the partials is calling things like > .humanize which capitalize text and I am not really concerned about those > details in my test.......... > > > So the way I got my test passing is to do: > > @presenter.output.gsub("\n", "").gsub("'", "\"").downcase.should == filter_for_html(' ... same content as before ... ') > > Which I don't know about you, but that makes me go "ewwwwwwwwww". And makes > all the RSpec readibility go out the window. Is there something I should be > doing with a custom matcher or something to test for case-indifferent text, > ignore whitespace and \n, and be quote indifferent? > > Thanks. > > Patrick J. Collins > http://collinatorstudios.com I realise this isn't the answer you're looking for, but I'm curious: where did you get the idea that a presenter should know anything about HTML? cheers, Matt -- Freelance programmer & coach Author, http://pragprog.com/book/hwcuc/the-cucumber-book (with Aslak Helles?y) Founder, http://relishapp.com +44(0)7974430184 | http://twitter.com/mattwynne From patrick at collinatorstudios.com Thu Nov 3 19:25:42 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Thu, 3 Nov 2011 16:25:42 -0700 (PDT) Subject: [rspec-users] problems matching generated html output... In-Reply-To: <1E3AE5CF-5D6A-4F1D-B41C-F1762C5DBC94@mattwynne.net> References: <1E3AE5CF-5D6A-4F1D-B41C-F1762C5DBC94@mattwynne.net> Message-ID: > I realise this isn't the answer you're looking for, but I'm curious: where > did you get the idea that a presenter should know anything about HTML? Maybe I am using the wrong terminology then. I always thought presenters were classes that output presentational content... If you have a view with a lot of dynamic content, the conditional logic ends up building to the point where the view is unreadable, and if you try to refactor out into helper methods, you end up having something like module MyHelper def something(lol) modify_lol(lol) end def modify_lol(lol) do_something_else_with_lol(lol) end ... etc end A class helps to eliminate this problem by giving you a way to instantiate with instance variables and cut down on having pass around the same variable to multiple helpers...... I've always called that a presenter, and in this case it deals with HTML. Am I totally on crack? Patrick J. Collins http://collinatorstudios.com From patmaddox at me.com Thu Nov 3 20:47:42 2011 From: patmaddox at me.com (Pat Maddox) Date: Thu, 03 Nov 2011 17:47:42 -0700 Subject: [rspec-users] problems matching generated html output... In-Reply-To: References: Message-ID: <2FEDAE22-149A-4B98-9BA4-C421E3A4A9C0@me.com> On Nov 3, 2011, at 4:07 PM, Patrick J. Collins wrote: >> So, I am writing tests for a presenter class that outputs html markup. >> > Actually now that I am thinking about it.. Would you guys recommend that I use > something like Nokogiri to parse the content and test for things like number of > children, classes, ids, etc, rather than just comparing the raw HTML? Yes, definitely. Also you might be interested in https://github.com/nakajima/elementor although I haven't used it in a long time so I don't know how up to date it is. As far as your other question goes about how to use presenters, you probably don't want them emitting HTML. Instead you want the presenter to provide a simpler interface to some commonly accessed data that you don't think belongs on the model. An example might be class UserPresenter def initialize(user) @user = user end def full_name @user.first_name + ' ' + @user.last_name end end Ignoring whether this is an appropriate case for using a presenter, you can see what I'm accomplishing here. And hopefully you can imagine it being more useful if there are multiple models involved. A presenter is basically the facade pattern used specifically for presentation logic. Pat http://c2.com/cgi/wiki?FacadePattern http://blog.jayfields.com/2007/03/rails-presenter-pattern.html From matt at mattwynne.net Fri Nov 4 05:24:14 2011 From: matt at mattwynne.net (Matt Wynne) Date: Fri, 4 Nov 2011 09:24:14 +0000 Subject: [rspec-users] problems matching generated html output... In-Reply-To: References: <1E3AE5CF-5D6A-4F1D-B41C-F1762C5DBC94@mattwynne.net> Message-ID: <09E9D56B-F97B-4478-BB52-9384626EB667@mattwynne.net> On 3 Nov 2011, at 23:25, Patrick J. Collins wrote: >> I realise this isn't the answer you're looking for, but I'm curious: where >> did you get the idea that a presenter should know anything about HTML? > > Maybe I am using the wrong terminology then. I always thought presenters were > classes that output presentational content Well, in any discussion I've seen of the pattern, that's the job of the view. MVP / Passive View[1][2] is quite a well-established pattern in curly-bracket languages, and the presenter's job in that pattern is to tell the view, at a logical level, what to show. The view is then just left with the simple job of showing it. The idea being that you could use the same presenter with a view for a web app, a view for a rich-client GUI, or a view for a mobile app. In theory. This makes them both much easier to test. Steve Klabnik has been writing about their application in the Ruby / Rails world recently[3] [1] http://martinfowler.com/eaaDev/PassiveScreen.html [2] http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf [3] http://blog.steveklabnik.com/2011/09/06/the-secret-to-rails-oo-design.html cheers, Matt -- Freelance programmer & coach Author, http://pragprog.com/book/hwcuc/the-cucumber-book (with Aslak Helles?y) Founder, http://relishapp.com +44(0)7974430184 | http://twitter.com/mattwynne -------------- next part -------------- An HTML attachment was scrubbed... URL: From denise.mauldin at gmail.com Fri Nov 4 15:22:39 2011 From: denise.mauldin at gmail.com (Denise Mauldin) Date: Fri, 4 Nov 2011 12:22:39 -0700 Subject: [rspec-users] Rspec help Message-ID: <9FDE580E-DC7D-4598-AFFC-05B87E4F9CB0@gmail.com> Hi all I've created a stack overflow question that I hope someone here can help me with. http://stackoverflow.com/questions/8002318/ruby-rails-rspec-local-variables Thanks in advance, Denise From david.hofer at gmail.com Tue Nov 1 13:59:14 2011 From: david.hofer at gmail.com (David Hofer) Date: Tue, 1 Nov 2011 10:59:14 -0700 (PDT) Subject: [rspec-users] Weird behavior with should_not_receive Message-ID: I recently saw a test passing when it should have failed, because the person who wrote it used should_not_receive instead of should_receive. Here is a simple example illustrating the behavior: class MyTest def foo puts "hey" end def bar foo end end describe MyTest do it "passes but should fail" do subject.should_not_receive(:foo).once subject.bar end end If I remove the ".once" the test fails, as I would expect. Is this intended behavior? It seems really weird to me. I am seeing this with rspec 1.3.2 and rspec-rails 1.3.4. Thanks, David From brambomail at gmail.com Wed Nov 2 18:41:44 2011 From: brambomail at gmail.com (Bram) Date: Wed, 2 Nov 2011 15:41:44 -0700 (PDT) Subject: [rspec-users] any_instance Message-ID: <410b04d0-f776-4cec-83eb-606b0c1d703c@o5g2000yqa.googlegroups.com> Hello, I'm trying to stub out a method with the any_instance method, this works well if I run the spec individually however when I do a full run it will call the actual method: example "" do Library::Class.any_instance.stub(:method).and_return true Model.create end This will fire off the before_save method in ModelObserver and call Library::Class.method. running "bundle exec rspec spec/observer/model_observer.rb" works "bundle exec rspec" will call the actual method. Any clues as to what could be wrong? Thanks in advanced. From dchelimsky at gmail.com Sun Nov 6 15:46:11 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 6 Nov 2011 14:46:11 -0600 Subject: [rspec-users] Weird behavior with should_not_receive In-Reply-To: References: Message-ID: <28F0016D-64A8-45C5-BC75-F21D349FDBB4@gmail.com> On Nov 1, 2011, at 12:59 PM, David Hofer wrote: > I recently saw a test passing when it should have failed, because the > person who wrote it used should_not_receive instead of > should_receive. Here is a simple example illustrating the behavior: > > class MyTest > def foo > puts "hey" > end > > def bar > foo > end > end > > describe MyTest do > it "passes but should fail" do > subject.should_not_receive(:foo).once > subject.bar > end > end > > If I remove the ".once" the test fails, as I would expect. > > Is this intended behavior? It seems really weird to me. > > I am seeing this with rspec 1.3.2 and rspec-rails 1.3.4. It is really weird, but it's also a misunderstanding of the API. should_receive(:foo) defaults to an expectation of 1 time. The object then exposes methods like once, twice, exactly(3).times to specify/modify the expectation: foo.should_receive(:bar).once foo.should_receive(:bar).twice foo.should_receive(:bar).exactly(3).times Yes, I was sorely tempted to support foo.should_receive(:bar).three_times_a_lady when we added all that, but I refrained. Now that Siri will reenact the entire "Who's on first?" routine, I'm reconsidering. That aside, to specify that a message would not be received, we used to have to write: foo.should_receive(:bar).exactly(0).times We later added foo.should_not_receive(:bar) as a shorter, more expressive version of that. So, since methods like once, twice, exactly(n).times, at_least(n).times and at_most(n).times all modify the constraint, it turns out that they could be used together, like this: foo.should_receive(:bar).once.twice.exactly(3).times In this case, it would expect :bar 3 times, because the last modification wins. Of course you would never do that deliberately, and in my 5 1/2 years running this project this is the first time I've ever seen any issue w/ this, but that is actually not prevented. Therefore, the following are equivalent: foo.should_receive(:bar).exactly(0).times.once foo.should_not_receive(:bar).once Hope that helps you to understand the problem. In terms of what we can/will do about it, I don't really think we'll do anything about it but document it better. It would require too much work to solve this without breaking other things, and it turns out that mocha, flexmock, and RR all have the same issue: foo.expects(:bar).never.once flexmock(foo).should_receive(:bar).never.once mock(foo).bar.never.once Cheers, David From alex at stinky.com Sun Nov 6 17:45:42 2011 From: alex at stinky.com (Alex Chaffee) Date: Sun, 6 Nov 2011 14:45:42 -0800 Subject: [rspec-users] Weird behavior with should_not_receive In-Reply-To: <28F0016D-64A8-45C5-BC75-F21D349FDBB4@gmail.com> References: <28F0016D-64A8-45C5-BC75-F21D349FDBB4@gmail.com> Message-ID: Double negatives are not unconfusing. Not unlike chaining mutable decorator objects. (I was tempted to say "non-immutable" but that would chain the jokes) btw with .once and .twice, why not .thrice? Lady or no. -- Alex Chaffee - alex at stinky.com http://alexchaffee.com http://twitter.com/alexch -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Sun Nov 6 17:55:22 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 6 Nov 2011 16:55:22 -0600 Subject: [rspec-users] Weird behavior with should_not_receive In-Reply-To: References: <28F0016D-64A8-45C5-BC75-F21D349FDBB4@gmail.com> Message-ID: On Nov 6, 2011, at 4:45 PM, Alex Chaffee wrote: > Double negatives are not unconfusing. > > Not unlike chaining mutable decorator objects. > > (I was tempted to say "non-immutable" but that would chain the jokes) > > btw with .once and .twice, why not .thrice? Lady or no. module Thrice def thrice(&block) exactly(3).times &block end end RSpec::Mocks::MessageExpectation.send :include, Thrice There you go :) From dchelimsky at gmail.com Sun Nov 6 18:17:44 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 6 Nov 2011 17:17:44 -0600 Subject: [rspec-users] rspec-2.8.0.rc1 is released Message-ID: <08D04F55-151F-4542-ADEA-F69C1B3EFD88@gmail.com> http://blog.davidchelimsky.net/2011/11/06/rspec-280rc1-is-released/ See the blog post for more information, but highlights include: 1. tag overrides Now you can set tag/filter defaults in .rspec: --tag ~javascript or in RSpec.configure (in spec_helper.rb): RSpec.configure {|c| c.filter_run_excluding :javascript} and then override that from the command line when you want to run the javascript specs: rspec --tag javascript 2. --order rand Courtesy of Justin Ko, this addition allows you to run examples in random order. To make that your default, we recommend putting this in .rspec: --order rand Then you can override it from the command line like this: rspec --order default Or you specify a seed in two ways: rspec --order rand:1234 rspec --seed 1234 3. speed improvements in rspec-expectations YMMV, but all of the built-in matchers have been reimplemented as classes (they were previously generated using the DSL, which interprets a lot of code at invocation time). There's more info at http://blog.davidchelimsky.net/2011/11/06/rspec-280rc1-is-released/. Please give it a read, give rspec-2.8.0.rc1 a try, and report any issues to: * https://github.com/rspec/rspec-core/issues * https://github.com/rspec/rspec-expectations/issues * https://github.com/rspec/rspec-mocks/issues * https://github.com/rspec/rspec-rails/issues Thanks! David From ckponnappa at gmail.com Mon Nov 7 02:19:04 2011 From: ckponnappa at gmail.com (Sidu Ponnappa) Date: Mon, 7 Nov 2011 12:49:04 +0530 Subject: [rspec-users] any_instance In-Reply-To: <410b04d0-f776-4cec-83eb-606b0c1d703c@o5g2000yqa.googlegroups.com> References: <410b04d0-f776-4cec-83eb-606b0c1d703c@o5g2000yqa.googlegroups.com> Message-ID: > Any clues as to what could be wrong? It's either a bug or some other tests have side effects that only show up when run together. Let me try to replicate it on one of my codebases and get back to you. Best, Sidu Ponnappa. http://c42.in http://rubymonk.com On 3 November 2011 04:11, Bram wrote: > Hello, > > I'm trying to stub out a method with the any_instance method, this > works well if I run the spec individually however when I do a full run > it will call the actual method: > > > example "" do > ?Library::Class.any_instance.stub(:method).and_return true > ?Model.create > end > > This will fire off the before_save method in ModelObserver and call > Library::Class.method. > > running "bundle exec rspec spec/observer/model_observer.rb" works > "bundle exec rspec" will call the actual method. > > Any clues as to what could be wrong? > > Thanks in advanced. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From alex at stinky.com Mon Nov 7 07:53:59 2011 From: alex at stinky.com (Alex Chaffee) Date: Mon, 7 Nov 2011 04:53:59 -0800 Subject: [rspec-users] Weird behavior with should_not_receive In-Reply-To: References: <28F0016D-64A8-45C5-BC75-F21D349FDBB4@gmail.com> Message-ID: On Sun, Nov 6, 2011 at 2:55 PM, David Chelimsky wrote: > There you go :) > You are three times a gentleman, David. -- Alex Chaffee - alex at stinky.com http://alexchaffee.com http://twitter.com/alexch -------------- next part -------------- An HTML attachment was scrubbed... URL: From rob at stardotstar.com Wed Nov 2 14:01:30 2011 From: rob at stardotstar.com (Rob Aldred) Date: Wed, 2 Nov 2011 18:01:30 +0000 Subject: [rspec-users] Setting expections on chained calls Message-ID: <20111102180130.GA10088@Rob-Aldreds-Mac-mini.local> I'm pretty sure this has probably been discussed before. I'm using couchdb (couchrest_model) When speccing my controller i want to set expectations that im calling my couch views correctly. The query interface has recently been updated to work very similar to ARel This means i have to rewrite some of my specs. Old call: Exam.by_created_at_and_not_archived(:start_key => [@exam.created_at], :endkey => ['0'],:limit => 2) I set an expectation on that easily like so: Exam.should_receive(:by_created_at_and_not_archived). with(:startkey => [@exam1.created_at],:endkey => ['0'],:limit => 2). and_return([@exam1, at exam2]) However the new api i doesn't seem that easy to work with: Exam.by_created_at_and_not_archived.startkey([@exam.created_at]).endkey(['0']).limit(2) I could use stub_chain, but that doesn't allow me to check the params being passes to the calls other than the last. I could also create a wrapper method on my Exam model that is called from the controller with hash params, however that just shifts the problem, I then have to check the expections in the model spec instead. Suggestions on how best to go about that would be appreciated. From jko170 at gmail.com Mon Nov 7 13:37:50 2011 From: jko170 at gmail.com (Justin Ko) Date: Mon, 7 Nov 2011 11:37:50 -0700 Subject: [rspec-users] Setting expections on chained calls In-Reply-To: <20111102180130.GA10088@Rob-Aldreds-Mac-mini.local> References: <20111102180130.GA10088@Rob-Aldreds-Mac-mini.local> Message-ID: <2707D8DA-59EB-49F5-8EBA-C0961CA217DB@gmail.com> On Nov 2, 2011, at 12:01 PM, Rob Aldred wrote: > > I'm pretty sure this has probably been discussed before. > I'm using couchdb (couchrest_model) > > When speccing my controller i want to set expectations that im calling my couch views correctly. > The query interface has recently been updated to work very similar to ARel > > This means i have to rewrite some of my specs. > > Old call: > > Exam.by_created_at_and_not_archived(:start_key => [@exam.created_at], :endkey => ['0'],:limit => 2) > > I set an expectation on that easily like so: > > Exam.should_receive(:by_created_at_and_not_archived). > with(:startkey => [@exam1.created_at],:endkey => ['0'],:limit => 2). > and_return([@exam1, at exam2]) > > However the new api i doesn't seem that easy to work with: > > Exam.by_created_at_and_not_archived.startkey([@exam.created_at]).endkey(['0']).limit(2) > > I could use stub_chain, but that doesn't allow me to check the params being passes to the calls other than the last. > I could also create a wrapper method on my Exam model that is called from the controller with hash params, > however that just shifts the problem, I then have to check the expections in the model spec instead. > > Suggestions on how best to go about that would be appreciated. > > > > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users Exam.should_receive(:by_created_at_and_not_archived).and_return( double('startkey').tap {|startkey| startkey.should_receive(:startkey).with([@exam.created_at]).and_return( double('endkey').tap {|endkey| endkey.should_receive(:endkey).with(['0']).and_return( double('limit').tap {|limit| limit.should_receive(:limit).with(2).and_return([@exam1, @exam2]) } ) } ) } ) LOL, this is the ugliest code I've written all year. You'd might want to use variables for readability: endkey = double('endkey') startkey = double('startkey') startkey.should_receive(:start key).with([@exam.created_at]) { endkey } From matt at mattwynne.net Mon Nov 7 18:13:19 2011 From: matt at mattwynne.net (Matt Wynne) Date: Mon, 7 Nov 2011 23:13:19 +0000 Subject: [rspec-users] Setting expections on chained calls In-Reply-To: <2707D8DA-59EB-49F5-8EBA-C0961CA217DB@gmail.com> References: <20111102180130.GA10088@Rob-Aldreds-Mac-mini.local> <2707D8DA-59EB-49F5-8EBA-C0961CA217DB@gmail.com> Message-ID: On 7 Nov 2011, at 18:37, Justin Ko wrote: > On Nov 2, 2011, at 12:01 PM, Rob Aldred wrote: > >> >> I'm pretty sure this has probably been discussed before. >> I'm using couchdb (couchrest_model) >> >> When speccing my controller i want to set expectations that im calling my couch views correctly. >> The query interface has recently been updated to work very similar to ARel >> >> This means i have to rewrite some of my specs. >> >> Old call: >> >> Exam.by_created_at_and_not_archived(:start_key => [@exam.created_at], :endkey => ['0'],:limit => 2) >> >> I set an expectation on that easily like so: >> >> Exam.should_receive(:by_created_at_and_not_archived). >> with(:startkey => [@exam1.created_at],:endkey => ['0'],:limit => 2). >> and_return([@exam1, at exam2]) >> >> However the new api i doesn't seem that easy to work with: >> >> Exam.by_created_at_and_not_archived.startkey([@exam.created_at]).endkey(['0']).limit(2) >> >> I could use stub_chain, but that doesn't allow me to check the params being passes to the calls other than the last. >> I could also create a wrapper method on my Exam model that is called from the controller with hash params, >> however that just shifts the problem, I then have to check the expections in the model spec instead. >> >> Suggestions on how best to go about that would be appreciated. >> >> >> >> >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users > > Exam.should_receive(:by_created_at_and_not_archived).and_return( > double('startkey').tap {|startkey| > startkey.should_receive(:startkey).with([@exam.created_at]).and_return( > double('endkey').tap {|endkey| > endkey.should_receive(:endkey).with(['0']).and_return( > double('limit').tap {|limit| > limit.should_receive(:limit).with(2).and_return([@exam1, @exam2]) > } > ) > } > ) > } > ) > > LOL, this is the ugliest code I've written all year. You'd might want to use variables for readability: ...or even wrap this Exam thing in an abstraction layer? Can anyone else hear the tests screaming? :) cheers, Matt -- Freelance programmer & coach Author, http://pragprog.com/book/hwcuc/the-cucumber-book (with Aslak Helles?y) Founder, http://relishapp.com +44(0)7974430184 | http://twitter.com/mattwynne From jko170 at gmail.com Mon Nov 7 19:36:22 2011 From: jko170 at gmail.com (Justin Ko) Date: Mon, 7 Nov 2011 17:36:22 -0700 Subject: [rspec-users] Setting expections on chained calls In-Reply-To: References: <20111102180130.GA10088@Rob-Aldreds-Mac-mini.local> <2707D8DA-59EB-49F5-8EBA-C0961CA217DB@gmail.com> Message-ID: <276F7ACD-C9B4-428E-93E1-6AE391A38205@gmail.com> On Nov 7, 2011, at 4:13 PM, Matt Wynne wrote: > > On 7 Nov 2011, at 18:37, Justin Ko wrote: > >> On Nov 2, 2011, at 12:01 PM, Rob Aldred wrote: >> >>> >>> I'm pretty sure this has probably been discussed before. >>> I'm using couchdb (couchrest_model) >>> >>> When speccing my controller i want to set expectations that im calling my couch views correctly. >>> The query interface has recently been updated to work very similar to ARel >>> >>> This means i have to rewrite some of my specs. >>> >>> Old call: >>> >>> Exam.by_created_at_and_not_archived(:start_key => [@exam.created_at], :endkey => ['0'],:limit => 2) >>> >>> I set an expectation on that easily like so: >>> >>> Exam.should_receive(:by_created_at_and_not_archived). >>> with(:startkey => [@exam1.created_at],:endkey => ['0'],:limit => 2). >>> and_return([@exam1, at exam2]) >>> >>> However the new api i doesn't seem that easy to work with: >>> >>> Exam.by_created_at_and_not_archived.startkey([@exam.created_at]).endkey(['0']).limit(2) >>> >>> I could use stub_chain, but that doesn't allow me to check the params being passes to the calls other than the last. >>> I could also create a wrapper method on my Exam model that is called from the controller with hash params, >>> however that just shifts the problem, I then have to check the expections in the model spec instead. >>> >>> Suggestions on how best to go about that would be appreciated. >>> >>> >>> >>> >>> _______________________________________________ >>> rspec-users mailing list >>> rspec-users at rubyforge.org >>> http://rubyforge.org/mailman/listinfo/rspec-users >> >> Exam.should_receive(:by_created_at_and_not_archived).and_return( >> double('startkey').tap {|startkey| >> startkey.should_receive(:startkey).with([@exam.created_at]).and_return( >> double('endkey').tap {|endkey| >> endkey.should_receive(:endkey).with(['0']).and_return( >> double('limit').tap {|limit| >> limit.should_receive(:limit).with(2).and_return([@exam1, @exam2]) >> } >> ) >> } >> ) >> } >> ) >> >> LOL, this is the ugliest code I've written all year. You'd might want to use variables for readability: > > ...or even wrap this Exam thing in an abstraction layer? Can anyone else hear the tests screaming? Personally, I wouldn't mock this code at all. It's a data retrieval method, let it hit CouchDB (abstracted or not). > > :) > > cheers, > Matt > > -- > Freelance programmer & coach > Author, http://pragprog.com/book/hwcuc/the-cucumber-book (with Aslak Helles?y) > Founder, http://relishapp.com > +44(0)7974430184 | http://twitter.com/mattwynne > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From robert.dober at gmail.com Tue Nov 8 02:02:19 2011 From: robert.dober at gmail.com (Robert Dober) Date: Tue, 8 Nov 2011 07:02:19 +0000 (UTC) Subject: [rspec-users] Invitation to connect on LinkedIn Message-ID: <1494669362.933014.1320735739523.JavaMail.app@ela4-bed84.prod> I'd like to add you to my professional network on LinkedIn. - Robert Robert Dober Developpeur Ruby On Rails et Javascript. at Up & Net Paris Area, France Confirm that you know Robert Dober: https://www.linkedin.com/e/c0fwx7-guqjyirk-5c/isd/4834432047/7mvOezRl/?hs=false&tok=2cXzLXCJlCUkY1 -- You are receiving Invitation to Connect emails. Click to unsubscribe: http://www.linkedin.com/e/c0fwx7-guqjyirk-5c/IvymfWqycahrnXkIwHGwgZqJcdGopgOdxFyMIpp/goo/rspec-users%40rubyforge%2Eorg/20061/I1681354953_1/?hs=false&tok=3tbIKawWdCUkY1 (c) 2011 LinkedIn Corporation. 2029 Stierlin Ct, Mountain View, CA 94043, USA. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rob at stardotstar.com Tue Nov 8 05:29:10 2011 From: rob at stardotstar.com (Rob Aldred) Date: Tue, 8 Nov 2011 10:29:10 +0000 Subject: [rspec-users] Setting expections on chained calls In-Reply-To: <276F7ACD-C9B4-428E-93E1-6AE391A38205@gmail.com> References: <20111102180130.GA10088@Rob-Aldreds-Mac-mini.local> <2707D8DA-59EB-49F5-8EBA-C0961CA217DB@gmail.com> <276F7ACD-C9B4-428E-93E1-6AE391A38205@gmail.com> Message-ID: <20111108102904.GB40648@Rob-Aldreds-Mac-mini.local> On Tue, Nov 08, 2011 at 12:36:22AM +0000, Justin Ko wrote: > > On Nov 7, 2011, at 4:13 PM, Matt Wynne wrote: > > > > > On 7 Nov 2011, at 18:37, Justin Ko wrote: > > > >> On Nov 2, 2011, at 12:01 PM, Rob Aldred wrote: > >> > >>> > >>> I'm pretty sure this has probably been discussed before. > >>> I'm using couchdb (couchrest_model) > >>> > >>> When speccing my controller i want to set expectations that im calling my couch views correctly. > >>> The query interface has recently been updated to work very similar to ARel > >>> > >>> This means i have to rewrite some of my specs. > >>> > >>> Old call: > >>> > >>> Exam.by_created_at_and_not_archived(:start_key => [@exam.created_at], :endkey => ['0'],:limit => 2) > >>> > >>> I set an expectation on that easily like so: > >>> > >>> Exam.should_receive(:by_created_at_and_not_archived). > >>> with(:startkey => [@exam1.created_at],:endkey => ['0'],:limit => 2). > >>> and_return([@exam1, at exam2]) > >>> > >>> However the new api i doesn't seem that easy to work with: > >>> > >>> Exam.by_created_at_and_not_archived.startkey([@exam.created_at]).endkey(['0']).limit(2) > >>> > >>> I could use stub_chain, but that doesn't allow me to check the params being passes to the calls other than the last. > >>> I could also create a wrapper method on my Exam model that is called from the controller with hash params, > >>> however that just shifts the problem, I then have to check the expections in the model spec instead. > >>> > >>> Suggestions on how best to go about that would be appreciated. > >>> > >>> > >>> > >>> > >>> _______________________________________________ > >>> rspec-users mailing list > >>> rspec-users at rubyforge.org > >>> http://rubyforge.org/mailman/listinfo/rspec-users > >> > >> Exam.should_receive(:by_created_at_and_not_archived).and_return( > >> double('startkey').tap {|startkey| > >> startkey.should_receive(:startkey).with([@exam.created_at]).and_return( > >> double('endkey').tap {|endkey| > >> endkey.should_receive(:endkey).with(['0']).and_return( > >> double('limit').tap {|limit| > >> limit.should_receive(:limit).with(2).and_return([@exam1, @exam2]) > >> } > >> ) > >> } > >> ) > >> } > >> ) > >> > >> LOL, this is the ugliest code I've written all year. You'd might want to use variables for readability: > > > > ...or even wrap this Exam thing in an abstraction layer? Can anyone else hear the tests screaming? > > Personally, I wouldn't mock this code at all. It's a data retrieval method, let it hit CouchDB (abstracted or not). > > > > > :) > > > > cheers, > > Matt > > > > -- > > Freelance programmer & coach > > Author, http://pragprog.com/book/hwcuc/the-cucumber-book (with Aslak Helles?y) > > Founder, http://relishapp.com > > +44(0)7974430184 | http://twitter.com/mattwynne > > > > _______________________________________________ > > rspec-users mailing list > > rspec-users at rubyforge.org > > http://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users Heh, that's magic. So maybe it's just better to create the documents in couch... I'm happy to do that, I just figured it would drastically effect performance of the tests. Rob From jko170 at gmail.com Tue Nov 8 10:01:15 2011 From: jko170 at gmail.com (Justin Ko) Date: Tue, 8 Nov 2011 08:01:15 -0700 Subject: [rspec-users] Setting expections on chained calls In-Reply-To: <20111108102904.GB40648@Rob-Aldreds-Mac-mini.local> References: <20111102180130.GA10088@Rob-Aldreds-Mac-mini.local> <2707D8DA-59EB-49F5-8EBA-C0961CA217DB@gmail.com> <276F7ACD-C9B4-428E-93E1-6AE391A38205@gmail.com> <20111108102904.GB40648@Rob-Aldreds-Mac-mini.local> Message-ID: On Nov 8, 2011, at 3:29 AM, Rob Aldred wrote: > On Tue, Nov 08, 2011 at 12:36:22AM +0000, Justin Ko wrote: >> >> On Nov 7, 2011, at 4:13 PM, Matt Wynne wrote: >> >>> >>> On 7 Nov 2011, at 18:37, Justin Ko wrote: >>> >>>> On Nov 2, 2011, at 12:01 PM, Rob Aldred wrote: >>>> >>>>> >>>>> I'm pretty sure this has probably been discussed before. >>>>> I'm using couchdb (couchrest_model) >>>>> >>>>> When speccing my controller i want to set expectations that im calling my couch views correctly. >>>>> The query interface has recently been updated to work very similar to ARel >>>>> >>>>> This means i have to rewrite some of my specs. >>>>> >>>>> Old call: >>>>> >>>>> Exam.by_created_at_and_not_archived(:start_key => [@exam.created_at], :endkey => ['0'],:limit => 2) >>>>> >>>>> I set an expectation on that easily like so: >>>>> >>>>> Exam.should_receive(:by_created_at_and_not_archived). >>>>> with(:startkey => [@exam1.created_at],:endkey => ['0'],:limit => 2). >>>>> and_return([@exam1, at exam2]) >>>>> >>>>> However the new api i doesn't seem that easy to work with: >>>>> >>>>> Exam.by_created_at_and_not_archived.startkey([@exam.created_at]).endkey(['0']).limit(2) >>>>> >>>>> I could use stub_chain, but that doesn't allow me to check the params being passes to the calls other than the last. >>>>> I could also create a wrapper method on my Exam model that is called from the controller with hash params, >>>>> however that just shifts the problem, I then have to check the expections in the model spec instead. >>>>> >>>>> Suggestions on how best to go about that would be appreciated. >>>>> >>>>> >>>>> >>>>> >>>>> _______________________________________________ >>>>> rspec-users mailing list >>>>> rspec-users at rubyforge.org >>>>> http://rubyforge.org/mailman/listinfo/rspec-users >>>> >>>> Exam.should_receive(:by_created_at_and_not_archived).and_return( >>>> double('startkey').tap {|startkey| >>>> startkey.should_receive(:startkey).with([@exam.created_at]).and_return( >>>> double('endkey').tap {|endkey| >>>> endkey.should_receive(:endkey).with(['0']).and_return( >>>> double('limit').tap {|limit| >>>> limit.should_receive(:limit).with(2).and_return([@exam1, @exam2]) >>>> } >>>> ) >>>> } >>>> ) >>>> } >>>> ) >>>> >>>> LOL, this is the ugliest code I've written all year. You'd might want to use variables for readability: >>> >>> ...or even wrap this Exam thing in an abstraction layer? Can anyone else hear the tests screaming? >> >> Personally, I wouldn't mock this code at all. It's a data retrieval method, let it hit CouchDB (abstracted or not). >> >>> >>> :) >>> >>> cheers, >>> Matt >>> >>> -- >>> Freelance programmer & coach >>> Author, http://pragprog.com/book/hwcuc/the-cucumber-book (with Aslak Helles?y) >>> Founder, http://relishapp.com >>> +44(0)7974430184 | http://twitter.com/mattwynne >>> >>> _______________________________________________ >>> rspec-users mailing list >>> rspec-users at rubyforge.org >>> http://rubyforge.org/mailman/listinfo/rspec-users >> >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users > > > Heh, that's magic. > So maybe it's just better to create the documents in couch... > I'm happy to do that, I just figured it would drastically effect performance of the tests. Create the docs and test it in Isolation. If you're worried about performance, mock the abstracted method everywhere else. > > Rob > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From lille.penguini at gmail.com Tue Nov 8 18:06:27 2011 From: lille.penguini at gmail.com (Lille) Date: Tue, 8 Nov 2011 15:06:27 -0800 (PST) Subject: [rspec-users] quick question on rspec-rails for Rails 3: how to stub AR class methods like :find? Message-ID: Hey, I recently switched to Rails 3(.1) and, using rspec-rails 2.6.1, I find can no longer stub AR class methods, like :find. So, where Comment is an AR class, I can't do this: Comment.should_receive(:find).and_return(... What is the new way of doing this, please? Lille From brucehobbs at engineeredsw.com Wed Nov 9 10:23:13 2011 From: brucehobbs at engineeredsw.com (Bruce Hobbs) Date: Wed, 9 Nov 2011 08:23:13 -0700 Subject: [rspec-users] RSpec file name with non-ASCII characters Message-ID: On Mac OS X 10.6.8 with Ruby 1.9.3, using a spec file name containing a non-ASCII character (an em-dash) I'm getting the error "in '=~': invalid byte sequence in US-ASCII (ArgumentError)" on this line self[:caller].detect {|l| l !~ /\/lib\/rspec\/core/} in the method "first_caller_from_outside_rspec" of the rspec-core-2.7.0/lib/rspec/core/metadata.rb file. Is there a simple fix, perhaps something other than "en_US.UTF-8" as the setting for the LANG environment variable, that wouldn't cause other issues? -- Bruce Hobbs, CCP, CDP Engineered Software Office: 626-570-8028 Partner 856 N Monterey St Cell: 626-278-0273 Alhambra, CA 91801-1574 FAX: 208-474-0732 From samirbraga at gmail.com Wed Nov 9 16:29:22 2011 From: samirbraga at gmail.com (Samir Braga) Date: Wed, 9 Nov 2011 19:29:22 -0200 Subject: [rspec-users] RSpec file name with non-ASCII characters In-Reply-To: References: Message-ID: Hello, have you tried to put # encoding: utf-8 in the begin of file? Maybe the answers in http://stackoverflow.com/questions/7699018/in-ruby-on-rails-are-encoding-utf-8-and-config-encoding-utf-8-differe can explain better this issue Regards On Wed, Nov 9, 2011 at 1:23 PM, Bruce Hobbs wrote: > On Mac OS X 10.6.8 with Ruby 1.9.3, using a spec file name containing a > non-ASCII character (an em-dash) I'm getting the error > > "in '=~': invalid byte sequence in US-ASCII (ArgumentError)" > > on this line > > self[:caller].detect {|l| l !~ /\/lib\/rspec\/core/} > > in the method "first_caller_from_outside_rspec" of the > rspec-core-2.7.0/lib/rspec/core/metadata.rb file. > > Is there a simple fix, perhaps something other than "en_US.UTF-8" as the > setting for the LANG environment variable, that wouldn't cause other > issues? > -- > Bruce Hobbs, CCP, CDP Engineered Software Office: 626-570-8028 > Partner 856 N Monterey St Cell: 626-278-0273 > Alhambra, CA 91801-1574 FAX: 208-474-0732 > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -------------- next part -------------- An HTML attachment was scrubbed... URL: From webervin at gmail.com Fri Nov 11 08:58:53 2011 From: webervin at gmail.com (Ervin) Date: Fri, 11 Nov 2011 05:58:53 -0800 (PST) Subject: [rspec-users] Problem with mocking helper methods Message-ID: Given that I assume that rails helper image_tag works as intended, I want to mock out call to this method in my helper. spec/helpers/some_helper_spec.rb: require 'spec_helper' describe SomeHelper do it 'allows stub tags' do helper.should_receive(:image_tag).with(2).and_return(3) helper.image_tag(2).should == 3 end end result: Failure/Error : helper.image_tag(2).should == 3 expected : 3 got : "\"2\"" (using ==) Bundle: * rspec (2.7.0) * rspec-core (2.7.1) * rspec-expectations (2.7.0) * rspec-mocks (2.7.0) * rspec-rails (2.7.0) * rails (3.1.1) From port001 at gmail.com Sat Nov 12 13:58:57 2011 From: port001 at gmail.com (Ian Leitch) Date: Sat, 12 Nov 2011 18:58:57 +0000 Subject: [rspec-users] Using require_relative to speed up rspec require time. Message-ID: Hi, I noticed recently that require 'rspec' on my machine was taking close to half a second. That's not a huge amount of time, but it is still the single slowest part of my test suite. It boils down to Ruby 1.9's rather slow require. I'm using 1.9.3, but I'd still like to shave off some of the require time. As an experiment, I went into rspec-core and rspec-expectations (the two biggest offenders) and replaced all require calls with require_relative. The benefits are actually quite impressive: rspec-core: before: 0.16s after: 0.10s rspec-expectations: before: 0.16s after: 0.05s Applying this to rspec-mocks also, my total require time for 'rspec' has gone from 0.5s to 0.21s. These are just quick a nasty timings, but there's obviously some win to be had. Would David, or the RSpec developers in general accept a patch to use require_relative if 1.9 is detected? Are there scenarios under which require_relative would not be possible? Cheers Ian From tspore at saassoft.com Sat Nov 12 16:33:08 2011 From: tspore at saassoft.com (Tony Spore) Date: Sat, 12 Nov 2011 13:33:08 -0800 Subject: [rspec-users] Testing Custom Methods Message-ID: I am attempting to test a custom method, and totally bombing out. describe Record do describe '#save_cf_data' do before :each do @record = mock_model(Record) end it "should have a birthday" do @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) @record.birth_day.should eql 3 end end My Model looks like this: class Record < ActiveRecord::Base def save_cf_data(params) result = params[:final_outputs].first .... self.birth_day = result['birth_day'].first end end I have this output - As if I'm not hitting the method correctly - Mock "Record_1002" received unexpected message :save_cf_data with ({"final_outputs"=>[{"birth_day"=>["3"]}]}) -Thanks, Tony Spore -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Sat Nov 12 17:06:46 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 12 Nov 2011 16:06:46 -0600 Subject: [rspec-users] Using require_relative to speed up rspec require time. In-Reply-To: References: Message-ID: <48866487-1470-466F-918B-03D2990D0CFB@gmail.com> On Nov 12, 2011, at 12:58 PM, Ian Leitch wrote: > Hi, > > I noticed recently that require 'rspec' on my machine was taking close > to half a second. That's not a huge amount of time, but it is still > the single slowest part of my test suite. > > It boils down to Ruby 1.9's rather slow require. I'm using 1.9.3, but > I'd still like to shave off some of the require time. > > As an experiment, I went into rspec-core and rspec-expectations (the > two biggest offenders) and replaced all require calls with > require_relative. The benefits are actually quite impressive: > > rspec-core: > before: 0.16s > after: 0.10s > > rspec-expectations: > before: 0.16s > after: 0.05s > > Applying this to rspec-mocks also, my total require time for 'rspec' > has gone from 0.5s to 0.21s. > > These are just quick a nasty timings, but there's obviously some win to be had. > > Would David, or the RSpec developers in general accept a patch to use > require_relative if 1.9 is detected? Are there scenarios under which > require_relative would not be possible? I can't think of a reason why this would be problematic, as long as we're not redefining existing methods that other code might be using. My only concern is the details of the implementation, and I'm not sure what I'd like to see there. Would you please file a pull request with just one of the libs (rspec-core is probably best) and once we get settled on the implementation details we can do it for the others. Cheers, David From dchelimsky at gmail.com Sat Nov 12 17:14:48 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 12 Nov 2011 16:14:48 -0600 Subject: [rspec-users] Testing Custom Methods In-Reply-To: References: Message-ID: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> On Nov 12, 2011, at 3:33 PM, Tony Spore wrote: > I am attempting to test a custom method, and totally bombing out. > describe Record do > describe '#save_cf_data' do > before :each do > @record = mock_model(Record) mock_model creates a test double, or pure mock ... > end > it "should have a birthday" do > @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) > @record.birth_day.should eql 3 ... which means that @record here ^^ is a test double, not a Record object ... > end > end > > My Model looks like this: > class Record < ActiveRecord::Base > def save_cf_data(params) > result = params[:final_outputs].first > .... > self.birth_day = result['birth_day'].first > end > end ... which means that this class definition ^^ has nothing to do with anything in the example above. > I have this output - As if I'm not hitting the method correctly - > Mock "Record_1002" received unexpected message :save_cf_data with ({"final_outputs"=>[{"birth_day"=>["3"]}]}) > What you want is either stub_model, or just Record.new or, if you're using something like factory_girl, Factory.build(Record). See https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-model and https://www.relishapp.com/rspec/rspec-rails/docs/mocks/stub-model for more info. HTH, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From brucehobbs at engineeredsw.com Sat Nov 12 18:28:30 2011 From: brucehobbs at engineeredsw.com (Bruce Hobbs) Date: Sat, 12 Nov 2011 15:28:30 -0800 Subject: [rspec-users] RSpec file name with non-ASCII characters Message-ID: At 19:29:22 -0200 on Wed, 9 Nov 2011, Samir Braga wrote: >Hello, have you tried to put > ># encoding: utf-8 > >in the begin of file? > I did try that, but it seems to make sense that it didn't work since, AFAICT, the problem is with the FQN of the spec file. >Maybe the answers in >http://stackoverflow.com/questions/7699018/in-ruby-on-rails-are-encoding-utf-8-and-config-encoding-utf-8-differe >can explain better this issue > If I'm understanding that discussion correctly it also addresses file contents not file names. -- Bruce Hobbs, CCP, CDP Engineered Software Office: 626-570-8028 Partner 856 N Monterey St Cell: 626-278-0273 Alhambra, CA 91801-1574 FAX: 208-474-0732 From tspore at saassoft.com Sat Nov 12 19:27:11 2011 From: tspore at saassoft.com (Tony Spore) Date: Sat, 12 Nov 2011 16:27:11 -0800 Subject: [rspec-users] Testing Custom Methods In-Reply-To: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> References: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> Message-ID: Great thanks! So now I am at least calling the method - But when I try to add in the params that I'm being sent I keep returning nil - Failure/Error: @record.save_cf_data(result) NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.delete In the above case I create the hash as result = {"final_outputs"=>["surname"=>["hagan"]]} When I manually place in the params - Failure/Error: @record.save_cf_data({"final_outputs"=>["surname"=>["hagan"]]}) NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.first So now as I go down this path, I would say that I am not feeding into the method my params. How would it be best to do that? I am right now just trying to use rspec with no additional params. Thanks again! -Thanks, Tony Spore On Sat, Nov 12, 2011 at 2:14 PM, David Chelimsky wrote: > On Nov 12, 2011, at 3:33 PM, Tony Spore wrote: > > I am attempting to test a custom method, and totally bombing out. > describe Record do > describe '#save_cf_data' do > before :each do > @record = mock_model(Record) > > > mock_model creates a test double, or pure mock ... > > end > it "should have a birthday" do > @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) > > @record.birth_day.should eql 3 > > > ... which means that @record here ^^ is a test double, not a Record object > ... > > end > end > > My Model looks like this: > class Record < ActiveRecord::Base > def save_cf_data(params) > result = params[:final_outputs].first > .... > self.birth_day = result['birth_day'].first > end > end > > > ... which means that this class definition ^^ has nothing to do with > anything in the example above. > > I have this output - As if I'm not hitting the method correctly - > > Mock "Record_1002" received unexpected message :save_cf_data with > ({"final_outputs"=>[{"birth_day"=>["3"]}]}) > > > What you want is either stub_model, or just Record.new or, if you're using > something like factory_girl, Factory.build(Record). > > See https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-model and > https://www.relishapp.com/rspec/rspec-rails/docs/mocks/stub-model for > more info. > > HTH, > David > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cnk at ugcs.caltech.edu Sat Nov 12 22:12:30 2011 From: cnk at ugcs.caltech.edu (Cynthia N. Kiser) Date: Sat, 12 Nov 2011 19:12:30 -0800 Subject: [rspec-users] Rspec not finding my examples Message-ID: <20111113031230.GA14616@ugcs.caltech.edu> I am following the examples in chapter 2 of "Rails 3 in Action" and for some reason I have to specify the full path + file name to get my specs to run. The book and rspec docs led me to believe that I should be able to just type 'rspec' and rspec would find any spec files in a directory called spec. I even tried adding a .rspec file with "--default_path spec" in the directory from which I am running rspec. No luck with that either. I am using RSpec 2.7.0 and Ruby 1.9.2 under RVM. My directory structure is: bacon lib bacon.rb spec bacon.spec >From the bacon directory: $ rspec No examples found. $ rspec spec No examples found. $ rspec spec/bacon.spec .. Finished in 1.09 seconds 2 examples, 0 failures -- Cynthia N. Kiser cnk at ugcs.caltech.edu From dchelimsky at gmail.com Sat Nov 12 23:47:36 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 12 Nov 2011 22:47:36 -0600 Subject: [rspec-users] Rspec not finding my examples In-Reply-To: <20111113031230.GA14616@ugcs.caltech.edu> References: <20111113031230.GA14616@ugcs.caltech.edu> Message-ID: On Nov 12, 2011, at 9:12 PM, "Cynthia N. Kiser" wrote: > I am following the examples in chapter 2 of "Rails 3 in Action" and > for some reason I have to specify the full path + file name to get my > specs to run. The book and rspec docs led me to believe that I should > be able to just type 'rspec' and rspec would find any spec files in a > directory called spec. I even tried adding a .rspec file with > "--default_path spec" in the directory from which I am running > rspec. No luck with that either. > > I am using RSpec 2.7.0 and Ruby 1.9.2 under RVM. > > > My directory structure is: > > bacon > lib > bacon.rb > spec > bacon.spec Make this bacon_spec.rb HTH, David From cnk at ugcs.caltech.edu Sun Nov 13 01:17:43 2011 From: cnk at ugcs.caltech.edu (Cynthia Kiser) Date: Sat, 12 Nov 2011 22:17:43 -0800 Subject: [rspec-users] Rspec not finding my examples In-Reply-To: References: <20111113031230.GA14616@ugcs.caltech.edu> Message-ID: <20111113061743.GA20711@ugcs.caltech.edu> Quoting David Chelimsky : > Make this bacon_spec.rb Ahhh so easy. Works great. Thanks. -- Cynthia N. Kiser cnk at ugcs.caltech.edu From dchelimsky at gmail.com Sun Nov 13 11:12:56 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 13 Nov 2011 10:12:56 -0600 Subject: [rspec-users] Testing Custom Methods In-Reply-To: References: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> Message-ID: On Nov 12, 2011, at 6:27 PM, Tony Spore wrote: > > > > > -Thanks, > Tony Spore > > > > On Sat, Nov 12, 2011 at 2:14 PM, David Chelimsky wrote: > On Nov 12, 2011, at 3:33 PM, Tony Spore wrote: > >> I am attempting to test a custom method, and totally bombing out. >> describe Record do >> describe '#save_cf_data' do >> before :each do >> @record = mock_model(Record) > > mock_model creates a test double, or pure mock ... > >> end >> it "should have a birthday" do >> @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) >> @record.birth_day.should eql 3 > > ... which means that @record here ^^ is a test double, not a Record object ... > >> end >> end >> >> My Model looks like this: >> class Record < ActiveRecord::Base >> def save_cf_data(params) >> result = params[:final_outputs].first >> .... >> self.birth_day = result['birth_day'].first >> end >> end > > ... which means that this class definition ^^ has nothing to do with anything in the example above. > >> I have this output - As if I'm not hitting the method correctly - >> Mock "Record_1002" received unexpected message :save_cf_data with ({"final_outputs"=>[{"birth_day"=>["3"]}]}) >> > > What you want is either stub_model, or just Record.new or, if you're using something like factory_girl, Factory.build(Record). > > See https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-model and https://www.relishapp.com/rspec/rspec-rails/docs/mocks/stub-model for more info. > > HTH, > David > Great thanks! > > So now I am at least calling the method - But when I try to add in the params that I'm being sent I keep returning nil - > Failure/Error: @record.save_cf_data(result) > NoMethodError: > You have a nil object when you didn't expect it! > You might have expected an instance of Array. > The error occurred while evaluating nil.delete > > In the above case I create the hash as result = {"final_outputs"=>["surname"=>["hagan"]]} > > When I manually place in the params - > Failure/Error: @record.save_cf_data({"final_outputs"=>["surname"=>["hagan"]]}) > NoMethodError: > You have a nil object when you didn't expect it! > You might have expected an instance of Array. > The error occurred while evaluating nil.first > > So now as I go down this path, I would say that I am not feeding into the method my params. How would it be best to do that? > > I am right now just trying to use rspec with no additional params. > > Thanks again! I'd love to help, but ... 1. please post either inline or at the bottom (I moved your post to the bottom in this case - see http://idallen.com/topposting.html). 2. please post actual code or a link to a gist instead of descriptions of the code or changes you made. And example is worth 10000 words, and it makes it easier for people who are trying to help to understand exactly what you're dealing with. Cheers, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From tspore at saassoft.com Sun Nov 13 17:54:38 2011 From: tspore at saassoft.com (Tony Spore) Date: Sun, 13 Nov 2011 14:54:38 -0800 Subject: [rspec-users] Testing Custom Methods In-Reply-To: References: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> Message-ID: Sorry David, I am getting this error: ailure/Error: @record.save_cf_data(result) NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.first Here is my Gist of my code that I can't figure out how to test. - https://gist.github.com/1362863 So I am expecting it to send in my result, but instead the test has nil. -Thanks, Tony Spore On Sun, Nov 13, 2011 at 8:12 AM, David Chelimsky wrote: > On Nov 12, 2011, at 6:27 PM, Tony Spore wrote: > > > > > > > -Thanks, > Tony Spore > > > On Sat, Nov 12, 2011 at 2:14 PM, David Chelimsky wrote: > >> On Nov 12, 2011, at 3:33 PM, Tony Spore wrote: >> >> I am attempting to test a custom method, and totally bombing out. >> describe Record do >> describe '#save_cf_data' do >> before :each do >> @record = mock_model(Record) >> >> >> mock_model creates a test double, or pure mock ... >> >> end >> it "should have a birthday" do >> @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) >> >> @record.birth_day.should eql 3 >> >> >> ... which means that @record here ^^ is a test double, not a Record >> object ... >> >> end >> end >> >> My Model looks like this: >> class Record < ActiveRecord::Base >> def save_cf_data(params) >> result = params[:final_outputs].first >> .... >> self.birth_day = result['birth_day'].first >> end >> end >> >> >> ... which means that this class definition ^^ has nothing to do with >> anything in the example above. >> >> I have this output - As if I'm not hitting the method correctly - >> >> Mock "Record_1002" received unexpected message :save_cf_data with >> ({"final_outputs"=>[{"birth_day"=>["3"]}]}) >> >> >> What you want is either stub_model, or just Record.new or, if you're >> using something like factory_girl, Factory.build(Record). >> >> See https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-modeland >> https://www.relishapp.com/rspec/rspec-rails/docs/mocks/stub-model for >> more info. >> >> HTH, >> David >> > > Great thanks! > > So now I am at least calling the method - But when I try to add in the > params that I'm being sent I keep returning nil - > Failure/Error: @record.save_cf_data(result) > NoMethodError: > You have a nil object when you didn't expect it! > You might have expected an instance of Array. > The error occurred while evaluating nil.delete > > In the above case I create the hash as result > = {"final_outputs"=>["surname"=>["hagan"]]} > > When I manually place in the params - > Failure/Error: > @record.save_cf_data({"final_outputs"=>["surname"=>["hagan"]]}) > NoMethodError: > You have a nil object when you didn't expect it! > You might have expected an instance of Array. > The error occurred while evaluating nil.first > > So now as I go down this path, I would say that I am not feeding into the > method my params. How would it be best to do that? > > I am right now just trying to use rspec with no additional params. > > Thanks again! > > > I'd love to help, but ... > > 1. please post either inline or at the bottom (I moved your post to the > bottom in this case - see http://idallen.com/topposting.html). > 2. please post actual code or a link to a gist instead of descriptions of > the code or changes you made. And example is worth 10000 words, and it > makes it easier for people who are trying to help to understand exactly > what you're dealing with. > > Cheers, > David > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Sun Nov 13 19:29:25 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 13 Nov 2011 18:29:25 -0600 Subject: [rspec-users] Testing Custom Methods In-Reply-To: References: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> Message-ID: <520053F0-E38E-46FA-AECE-C3490459AFA9@gmail.com> On Nov 13, 2011, at 4:54 PM, Tony Spore wrote: > On Sun, Nov 13, 2011 at 8:12 AM, David Chelimsky wrote: > On Nov 12, 2011, at 6:27 PM, Tony Spore wrote: > >> >> >> >> >> -Thanks, >> Tony Spore >> >> >> >> On Sat, Nov 12, 2011 at 2:14 PM, David Chelimsky wrote: >> On Nov 12, 2011, at 3:33 PM, Tony Spore wrote: >> >>> I am attempting to test a custom method, and totally bombing out. >>> describe Record do >>> describe '#save_cf_data' do >>> before :each do >>> @record = mock_model(Record) >> >> mock_model creates a test double, or pure mock ... >> >>> end >>> it "should have a birthday" do >>> @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) >>> @record.birth_day.should eql 3 >> >> ... which means that @record here ^^ is a test double, not a Record object ... >> >>> end >>> end >>> >>> My Model looks like this: >>> class Record < ActiveRecord::Base >>> def save_cf_data(params) >>> result = params[:final_outputs].first >>> .... >>> self.birth_day = result['birth_day'].first >>> end >>> end >> >> ... which means that this class definition ^^ has nothing to do with anything in the example above. >> >>> I have this output - As if I'm not hitting the method correctly - >>> Mock "Record_1002" received unexpected message :save_cf_data with ({"final_outputs"=>[{"birth_day"=>["3"]}]}) >>> >> >> What you want is either stub_model, or just Record.new or, if you're using something like factory_girl, Factory.build(Record). >> >> See https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-model and https://www.relishapp.com/rspec/rspec-rails/docs/mocks/stub-model for more info. >> >> HTH, >> David > >> Great thanks! >> >> So now I am at least calling the method - But when I try to add in the params that I'm being sent I keep returning nil - >> Failure/Error: @record.save_cf_data(result) >> NoMethodError: >> You have a nil object when you didn't expect it! >> You might have expected an instance of Array. >> The error occurred while evaluating nil.delete >> >> In the above case I create the hash as result = {"final_outputs"=>["surname"=>["hagan"]]} >> >> When I manually place in the params - >> Failure/Error: @record.save_cf_data({"final_outputs"=>["surname"=>["hagan"]]}) >> NoMethodError: >> You have a nil object when you didn't expect it! >> You might have expected an instance of Array. >> The error occurred while evaluating nil.first >> >> So now as I go down this path, I would say that I am not feeding into the method my params. How would it be best to do that? >> >> I am right now just trying to use rspec with no additional params. >> >> Thanks again! > > I'd love to help, but ... > > 1. please post either inline or at the bottom (I moved your post to the bottom in this case - see http://idallen.com/topposting.html). > 2. please post actual code or a link to a gist instead of descriptions of the code or changes you made. And example is worth 10000 words, and it makes it easier for people who are trying to help to understand exactly what you're dealing with. > > Cheers, > David > Moving your post to the bottom again .... > Sorry David, > I am getting this error: > ailure/Error: @record.save_cf_data(result) > NoMethodError: > You have a nil object when you didn't expect it! > You might have expected an instance of Array. > The error occurred while evaluating nil.first > > > Here is my Gist of my code that I can't figure out how to test. - > https://gist.github.com/1362863 > > So I am expecting it to send in my result, but instead the test has nil. The spec uses the string key "final_outputs", but the code uses the symbol key :final_outputs. HTH, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From tspore at saassoft.com Mon Nov 14 01:03:32 2011 From: tspore at saassoft.com (Tony Spore) Date: Sun, 13 Nov 2011 22:03:32 -0800 Subject: [rspec-users] Testing Custom Methods In-Reply-To: <520053F0-E38E-46FA-AECE-C3490459AFA9@gmail.com> References: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> <520053F0-E38E-46FA-AECE-C3490459AFA9@gmail.com> Message-ID: Thanks David. I am getting a long way now. -Thanks, Tony Spore CEO SaasSoft LLC (805) 253-1277 saassoft.com On Sun, Nov 13, 2011 at 4:29 PM, David Chelimsky wrote: > > On Nov 13, 2011, at 4:54 PM, Tony Spore wrote: > > On Sun, Nov 13, 2011 at 8:12 AM, David Chelimsky wrote: > >> On Nov 12, 2011, at 6:27 PM, Tony Spore wrote: >> >> >> >> >> >> >> -Thanks, >> Tony Spore >> >> >> On Sat, Nov 12, 2011 at 2:14 PM, David Chelimsky wrote: >> >>> On Nov 12, 2011, at 3:33 PM, Tony Spore wrote: >>> >>> I am attempting to test a custom method, and totally bombing out. >>> describe Record do >>> describe '#save_cf_data' do >>> before :each do >>> @record = mock_model(Record) >>> >>> >>> mock_model creates a test double, or pure mock ... >>> >>> end >>> it "should have a birthday" do >>> @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) >>> >>> @record.birth_day.should eql 3 >>> >>> >>> ... which means that @record here ^^ is a test double, not a Record >>> object ... >>> >>> end >>> end >>> >>> My Model looks like this: >>> class Record < ActiveRecord::Base >>> def save_cf_data(params) >>> result = params[:final_outputs].first >>> .... >>> self.birth_day = result['birth_day'].first >>> end >>> end >>> >>> >>> ... which means that this class definition ^^ has nothing to do with >>> anything in the example above. >>> >>> I have this output - As if I'm not hitting the method correctly - >>> >>> Mock "Record_1002" received unexpected message :save_cf_data with >>> ({"final_outputs"=>[{"birth_day"=>["3"]}]}) >>> >>> >>> What you want is either stub_model, or just Record.new or, if you're >>> using something like factory_girl, Factory.build(Record). >>> >>> See https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-modeland >>> https://www.relishapp.com/rspec/rspec-rails/docs/mocks/stub-model for >>> more info. >>> >>> HTH, >>> David >>> >> >> Great thanks! >> >> So now I am at least calling the method - But when I try to add in the >> params that I'm being sent I keep returning nil - >> Failure/Error: @record.save_cf_data(result) >> NoMethodError: >> You have a nil object when you didn't expect it! >> You might have expected an instance of Array. >> The error occurred while evaluating nil.delete >> >> In the above case I create the hash as result >> = {"final_outputs"=>["surname"=>["hagan"]]} >> >> When I manually place in the params - >> Failure/Error: >> @record.save_cf_data({"final_outputs"=>["surname"=>["hagan"]]}) >> NoMethodError: >> You have a nil object when you didn't expect it! >> You might have expected an instance of Array. >> The error occurred while evaluating nil.first >> >> So now as I go down this path, I would say that I am not feeding into the >> method my params. How would it be best to do that? >> >> I am right now just trying to use rspec with no additional params. >> >> Thanks again! >> >> >> I'd love to help, but ... >> >> 1. please post either inline or at the bottom (I moved your post to the >> bottom in this case - see http://idallen.com/topposting.html). >> 2. please post actual code or a link to a gist instead of descriptions of >> the code or changes you made. And example is worth 10000 words, and it >> makes it easier for people who are trying to help to understand exactly >> what you're dealing with. >> >> Cheers, >> David >> >> > Moving your post to the bottom again .... > > Sorry David, > I am getting this error: > ailure/Error: @record.save_cf_data(result) > NoMethodError: > You have a nil object when you didn't expect it! > You might have expected an instance of Array. > The error occurred while evaluating nil.first > > > Here is my Gist of my code that I can't figure out how to test. - > https://gist.github.com/1362863 > > So I am expecting it to send in my result, but instead the test has nil. > > The spec uses the string key "final_outputs", but the code uses the symbol > key :final_outputs. > HTH, > David > > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadridm at gmail.com Tue Nov 8 01:53:06 2011 From: emadridm at gmail.com (emadridm) Date: Mon, 7 Nov 2011 22:53:06 -0800 (PST) Subject: [rspec-users] How to write view specs with multiple forms Message-ID: <64907a24-ec46-4b2a-97e9-42c477ad0583@k10g2000yqn.googlegroups.com> Hi guys, I don't know how to write an spec for a view template with two or more forms. The follow content corresponds to the file named home.html.haml !!! 5 = form_for(:session, :url => sessions_path) do |f| .field = f.label :email = f.text_field :email .field = f.label :password = f.password_field :password .actions = f.submit "Sign in" = form_for(@user) do |f| .field = f.text_field :fullname .field = f.text_field :email .field = f.password_field :password .actions = f.submit "Sign up" The _spec file (home.html.haml_spec.rb) content is: require 'spec_helper' describe "pages/home.html.haml" do describe 'sign in form' do before(:each) do render end it 'should render a form to create a new session' do rendered.should have_selector("form", :method => "post", :action => sessions_path) do | form| form.should have_selector("input", :type => "submit", :value => "Sign in") end end end # describe: 'sign in form' describe 'sign up form' do let(:user) {mock_model("User").as_new_record.as_null_object} before(:each) do assign(:user, user) render end it 'should render a form to create a new user' do rendered.should have_selector("form", :method => "post", :action => users_path) do |form| form.should have_selector("input", :type => "submit", :value => "Sign up") end end end # describe: 'sign up form' end As this, the second example passes and the first doesn't. Rspec shows the message "undefined method model_name for Nilclass:Class". If I delete the second form, the first example passes. Anybody can tell me how to use have_selector properly? thanks a lot. From tribes.romain at gmail.com Tue Nov 8 01:52:40 2011 From: tribes.romain at gmail.com (Romain Tribes) Date: Mon, 7 Nov 2011 22:52:40 -0800 (PST) Subject: [rspec-users] Write tests for objects with lots of dependencies Message-ID: <21632501.695.1320735160942.JavaMail.geo-discussion-forums@yqcm23> Hello, I'm writing a Risk-like webgame (https://github.com/Sephi-Chan/Conquest-on-Rails) and I want to add tests, but it's painful since objects have a lot of dependencies each other. For instance, I have moved the attack logic in a dedicated class (https://github.com/Sephi-Chan/Conquest-on-Rails/blob/develop/app/models/attack.rb) and I would like to test it. The problem is that to test an attack, I need to have at least two ownerships (the relation between a territory and a participation). And to have two ownerships, I need to have many participations (the relation between a player and a game), and for that I need players. It's a lot of setup for a quite simple test. So, what should I do? Should I write a big setup for my suite? Or can I write a "sub-suites" with this big setup? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From thibaut.barrere at gmail.com Tue Nov 8 11:45:06 2011 From: thibaut.barrere at gmail.com (=?UTF-8?Q?Thibaut_Barr=C3=A8re?=) Date: Tue, 8 Nov 2011 08:45:06 -0800 (PST) Subject: [rspec-users] Wrong number of arguments (reduce, rspec/core/metadata) Message-ID: <14899485.422.1320770706406.JavaMail.geo-discussion-forums@vbbdd1> Hello, I'm a bit puzzled on this one. I'm getting a wrong number of arguments on a reduce call (full stack trace here: https://gist.github.com/1348309). Any idea where it could come from? (I tried with 2.7.1 and 2.8.0.rc1). FWIW, it's a Rails 2.3/RSpec 1 app that I'm migrating to Rails 3.0/RSpec 2. Any hint is most welcome! thanks, -- Thibaut -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at rentmineonline.com Tue Nov 8 11:52:43 2011 From: steve at rentmineonline.com (Stephen Kessler) Date: Tue, 8 Nov 2011 08:52:43 -0800 (PST) Subject: [rspec-users] set_fixture_class works on individual test, but test suite fails Message-ID: Hi all, I have a bug in my code that I have been unable to track down that deals with the set_fixture_class statement. Basically, set_fixture_class (and my tests) are working fine when I test one controller in isolation, but they are failing when I run all my controller specs together. My project use both a local database and Amazon Rds, and the tables on Amazon are namespaced with Rds::TableName. My controller spec looks something like: describe MyFirstController do set_fixture_class :users => Rds::User describe 'my test' do it 'should do something' do joe = users(:joe) end end end This works fine when running just this controller's spec. But when I run all the controller specs, the error I get is: Failure/Error: joe = users(:joe) FixtureClassNotFound: No class attached to find. I have isolated the problem to the interaction between two controller specs, MyFirstController (which contains set_fixture_class) and MySecondController (which does not contain set_fixture_class). When the tests for MyFirstController are run before the tests for MySecondController, everything works fine. But when the order is reversed, I get the above errors. Any ideas on what I might be able to do to fix this (besides requiring MyFirstController to run first)? From ivanpoval at gmail.com Tue Nov 8 17:40:21 2011 From: ivanpoval at gmail.com (ipoval) Date: Tue, 8 Nov 2011 14:40:21 -0800 (PST) Subject: [rspec-users] Are there plans to introduce conf.simplecov option? Message-ID: <7b3cf0c9-619c-4c56-8543-d50d2fed7b34@z22g2000prd.googlegroups.com> Hi, I wanted to ask if there are plans to introduce Rspec.configure { | conf| conf.simplecov = true } option? I understand that it is easy to add "require 'simplecov'; SimpleCov.start" into the spec_helper.rb, but it just doesn't look nice there. -- Thanks! From jeffdeville at gmail.com Thu Nov 10 12:10:26 2011 From: jeffdeville at gmail.com (JDeville) Date: Thu, 10 Nov 2011 09:10:26 -0800 (PST) Subject: [rspec-users] Is it possible to execute 'lets' once for all 'its'? Message-ID: <21829915.1394.1320945026148.JavaMail.geo-discussion-forums@yqcm23> The setup for certain integration specs is a bit slow, and I'm generally careful to make my 'it' blocks read-only. However, I also like to keep my it blocks extremely focused on just 1 thing. This has become a performance problem though, because the setup is executed for every 'it'. Is there any way to just run the setup once, and then the actual tests? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From webervin at gmail.com Fri Nov 11 07:48:13 2011 From: webervin at gmail.com (Ervin) Date: Fri, 11 Nov 2011 04:48:13 -0800 (PST) Subject: [rspec-users] Problem with mocking helper methods Message-ID: <14742ccb-41a5-4cfa-91f5-ccba44b02f63@n6g2000vbg.googlegroups.com> Given that I assume that rails helper image_tag works as intended, I want to mock out call to this method in my helper. spec/helpers/some_helper_spec.rb: require 'spec_helper' describe SomeHelper do it 'allows stub tags' do helper.should_receive(:image_tag).with(2).and_return(3) helper.image_tag(2).should == 3 end end result: Failure/Error : helper.image_tag(2).should == 3 expected : 3 got : "\"2\"" (using ==) Bundle: * rspec (2.7.0) * rspec-core (2.7.1) * rspec-expectations (2.7.0) * rspec-mocks (2.7.0) * rspec-rails (2.7.0) * rails (3.1.1) From tspore at saassoft.com Sat Nov 12 00:35:07 2011 From: tspore at saassoft.com (Tony Spore) Date: Fri, 11 Nov 2011 21:35:07 -0800 Subject: [rspec-users] Testing Custom methods Message-ID: I am attempting to test a custom method, and totally bombing out. describe Record do describe '#save_cf_data' do before :each do @record = mock_model(Record) end it "should have a birthday" do @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) @record.birth_day.should eql 3 end end My Model looks like this: class Record < ActiveRecord::Base def save_cf_data(params) result = params[:final_outputs].first .... self.birth_day = result['birth_day'].first end end I have this output - As if I'm not hitting the method correctly - Mock "Record_1002" received unexpected message :save_cf_data with ({"final_outputs"=>[{"birth_day"=>["3"]}]}) The actual code mostly works, I think I'm just sending rspec the wrong info. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From cnk at ugcs.caltech.edu Mon Nov 14 15:47:21 2011 From: cnk at ugcs.caltech.edu (Cynthia Kiser) Date: Mon, 14 Nov 2011 12:47:21 -0800 Subject: [rspec-users] Is it possible to execute 'lets' once for all 'its'? In-Reply-To: <21829915.1394.1320945026148.JavaMail.geo-discussion-forums@yqcm23> References: <21829915.1394.1320945026148.JavaMail.geo-discussion-forums@yqcm23> Message-ID: <20111114204721.GA28764@ugcs.caltech.edu> Quoting JDeville : > The setup for certain integration specs is a bit slow, and I'm generally > careful to make my 'it' blocks read-only. However, I also like to keep my > it blocks extremely focused on just 1 thing. This has become a performance > problem though, because the setup is executed for every 'it'. Is there any > way to just run the setup once, and then the actual tests? Just as there is a before(:each), there is a before(:all) which sounds like what you are looking for. RSpec 2 docs for this are at https://www.relishapp.com/rspec/rspec-core/v/2-0/docs/hooks/before-and-after-hooks -- Cynthia N. Kiser cnk at ugcs.caltech.edu From patrick at collinatorstudios.com Mon Nov 14 19:57:57 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Mon, 14 Nov 2011 16:57:57 -0800 (PST) Subject: [rspec-users] need some advice on the best way to structure testable shared methods Message-ID: So, I recognize that there are many different ways to accomplish what I am trying to do, but none of them seem to be as elegant as I would like. I have a few classes which need to have shared functionality... So I could do something like this: module NameBuilder def build_name(*args) args.shift.to_s + args.flatten.map {|component| "[#{component}]"}.join end end class Foo include NameBuilder def initialize(arg1, arg2) ... end end class Bar include NameBuilder def initialize(arg1, arg2) ... end end ... But, then I need to do something like: shared_examples "a nameable thingie" do |obj| describe "#build_name" do it "it adds the collection of arguments to the base components and formats them for a form element name attribute" do obj.build_name(:lol, :lollerskates, :roflcopter).should == "lol[lollerskates][roflcopter]" end end end describe Foo do it_behaves_like "a nameable thingie", Foo.new(nil, nil) end describe Bar do it_behaves_like "a nameable thingie", Bar.new(nil, nil) end Which I don't like, mainly because Foo & Bar's initialize methods require arguments, and I am having to do (nil, nil) which seems very uncool... ........... So, another approach would be to do: class Nameable def build_name(*args) args.shift.to_s + args.flatten.map {|component| "[#{component}]"}.join end end ... class Foo < Nameable ... end class Bar < Nameable ... end And then I can have a dedicated spec for Nameable and not worry about testing that in Foo and Bar... But, I am not 100% crazy about that approach either. Can anyone suggest a better way? Thanks! Patrick J. Collins http://collinatorstudios.com From cnk at ugcs.caltech.edu Mon Nov 14 21:22:50 2011 From: cnk at ugcs.caltech.edu (Cynthia Kiser) Date: Mon, 14 Nov 2011 18:22:50 -0800 Subject: [rspec-users] need some advice on the best way to structure testable shared methods In-Reply-To: References: Message-ID: <20111115022250.GA29724@ugcs.caltech.edu> Quoting Patrick J. Collins : > describe Bar do > it_behaves_like "a nameable thingie", Bar.new(nil, nil) > end > > Which I don't like, mainly because Foo & Bar's initialize methods require > arguments, and I am having to do (nil, nil) which seems very uncool... Having trouble following your example. Why do you have to pass Bar.new(nil, nil) for this test? -- Cynthia N. Kiser cnk at ugcs.caltech.edu From patrick at collinatorstudios.com Mon Nov 14 21:42:12 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Mon, 14 Nov 2011 18:42:12 -0800 (PST) Subject: [rspec-users] need some advice on the best way to structure testable shared methods In-Reply-To: <20111115022250.GA29724@ugcs.caltech.edu> References: <20111115022250.GA29724@ugcs.caltech.edu> Message-ID: > Having trouble following your example. Why do you have to pass > Bar.new(nil, nil) for this test? Because the shared example is testing the method #build_name from the module that is included in the various classes-- it needs the object that #build_name is attached to in order to test the functionality. The .new(nil, nil) is because the initialize method of the classes that include the module have expected arguments... I supposed I could have done def initialize(arg1 = nil, arg2 = nil) to prevent having to do Bar.new(nil, nil) in the test, but I actually would rather the init method have actual argument expectations. Patrick J. Collins http://collinatorstudios.com From dchelimsky at gmail.com Mon Nov 14 22:15:02 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 14 Nov 2011 21:15:02 -0600 Subject: [rspec-users] need some advice on the best way to structure testable shared methods In-Reply-To: References: Message-ID: On Nov 14, 2011, at 6:57 PM, Patrick J. Collins wrote: > So, I recognize that there are many different ways to accomplish what I am > trying to do, but none of them seem to be as elegant as I would like. > > I have a few classes which need to have shared functionality... > > So I could do something like this: > > module NameBuilder > > def build_name(*args) > args.shift.to_s + args.flatten.map {|component| "[#{component}]"}.join > end > > end > > class Foo > include NameBuilder > > def initialize(arg1, arg2) > ... > end > end > > class Bar > include NameBuilder > > def initialize(arg1, arg2) > ... > end > end > > ... > > But, then I need to do something like: > > shared_examples "a nameable thingie" do |obj| > > describe "#build_name" do > > it "it adds the collection of arguments to the base components and formats them for a form element name attribute" do > obj.build_name(:lol, :lollerskates, :roflcopter).should == "lol[lollerskates][roflcopter]" > end > > end > > end > > describe Foo do > it_behaves_like "a nameable thingie", Foo.new(nil, nil) > end > > describe Bar do > it_behaves_like "a nameable thingie", Bar.new(nil, nil) > end > > Which I don't like, mainly because Foo & Bar's initialize methods require > arguments, and I am having to do (nil, nil) which seems very uncool... Use the described class: shared_examples "a nameable thingie" do |klass| describe "#build_name" do it "it adds the collection of arguments to the base components and formats them for a form element name attribute" do described_class.new(nil,nil).build_name(:lol, :lollerskates, :roflcopter).should == "lol[lollerskates][roflcopter]" end end end describe Foo do it_behaves_like "a nameable thingie" end describe Bar do it_behaves_like "a nameable thingie" end Cheers, David From dchelimsky at gmail.com Mon Nov 14 22:26:49 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 14 Nov 2011 21:26:49 -0600 Subject: [rspec-users] How to write view specs with multiple forms In-Reply-To: <64907a24-ec46-4b2a-97e9-42c477ad0583@k10g2000yqn.googlegroups.com> References: <64907a24-ec46-4b2a-97e9-42c477ad0583@k10g2000yqn.googlegroups.com> Message-ID: <539DAA76-FB5B-413B-B689-BF948C271B74@gmail.com> On Nov 8, 2011, at 12:53 AM, emadridm wrote: > Hi guys, > > I don't know how to write an spec for a view template with two or more > forms. The follow content corresponds to the file named home.html.haml > > !!! 5 > = form_for(:session, :url => sessions_path) do |f| > .field > = f.label :email > = f.text_field :email > .field > = f.label :password > = f.password_field :password > .actions > = f.submit "Sign in" > = form_for(@user) do |f| > .field > = f.text_field :fullname > .field > = f.text_field :email > .field > = f.password_field :password > .actions > = f.submit "Sign up" > > The _spec file (home.html.haml_spec.rb) content is: > > require 'spec_helper' > > describe "pages/home.html.haml" do > > describe 'sign in form' do > > before(:each) do > render > end > > it 'should render a form to create a new session' do > rendered.should have_selector("form", > :method => "post", > :action => sessions_path) do | > form| > form.should have_selector("input", :type => "submit", :value > => "Sign in") > end > end > > end # describe: 'sign in form' > > describe 'sign up form' do > > let(:user) {mock_model("User").as_new_record.as_null_object} > > before(:each) do > assign(:user, user) > render > end > > it 'should render a form to create a new user' do > rendered.should have_selector("form", > :method => "post", > :action => users_path) do |form| > form.should have_selector("input", :type => "submit", :value > => "Sign up") > end > end > > end # describe: 'sign up form' > > end > > As this, the second example passes and the first doesn't. Rspec shows > the message "undefined method model_name for Nilclass:Class". If I > delete the second form, the first example passes. > > Anybody can tell me how to use have_selector properly? You've got to scope the forms so it can find both. Something like: .sign-in-form = form_for(:session, :url => sessions_path) do |f| ... .sign-up-form = form_for(@user) do |f| Now the spec can be more specific: rendered.should have_selector(".sign-in-form form", .... rendered.should have_selector(".sign-up-form form", .... HTH, David From dchelimsky at gmail.com Mon Nov 14 22:45:42 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 14 Nov 2011 21:45:42 -0600 Subject: [rspec-users] Wrong number of arguments (reduce, rspec/core/metadata) In-Reply-To: <14899485.422.1320770706406.JavaMail.geo-discussion-forums@vbbdd1> References: <14899485.422.1320770706406.JavaMail.geo-discussion-forums@vbbdd1> Message-ID: <3E3F4489-76B4-414B-976D-6083282AF757@gmail.com> On Nov 8, 2011, at 10:45 AM, Thibaut Barr?re wrote: > Hello, > > I'm a bit puzzled on this one. > > I'm getting a wrong number of arguments on a reduce call (full stack trace here: https://gist.github.com/1348309). > > Any idea where it could come from? (I tried with 2.7.1 and 2.8.0.rc1). > > FWIW, it's a Rails 2.3/RSpec 1 app that I'm migrating to Rails 3.0/RSpec 2. > > Any hint is most welcome! > > thanks, > > -- Thibaut reduce has a number of different forms, one of which is collection.reduce { ... } (with a block but no args). My best guess is either your app or another lib/gem is redefining reduce. Possible? From dchelimsky at gmail.com Mon Nov 14 22:49:49 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 14 Nov 2011 21:49:49 -0600 Subject: [rspec-users] Are there plans to introduce conf.simplecov option? In-Reply-To: <7b3cf0c9-619c-4c56-8543-d50d2fed7b34@z22g2000prd.googlegroups.com> References: <7b3cf0c9-619c-4c56-8543-d50d2fed7b34@z22g2000prd.googlegroups.com> Message-ID: On Nov 8, 2011, at 4:40 PM, ipoval wrote: > Hi, > > I wanted to ask if there are plans to introduce Rspec.configure { | > conf| conf.simplecov = true } option? > I understand that it is easy to add "require 'simplecov'; > SimpleCov.start" into the spec_helper.rb, but it just doesn't look > nice there. No plan yet. Please submit a feature request to https://github.com/rspec/rspec-core/issues and we can discuss it there. Cheers, David From dchelimsky at gmail.com Mon Nov 14 23:04:44 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 14 Nov 2011 22:04:44 -0600 Subject: [rspec-users] Write tests for objects with lots of dependencies In-Reply-To: <21632501.695.1320735160942.JavaMail.geo-discussion-forums@yqcm23> References: <21632501.695.1320735160942.JavaMail.geo-discussion-forums@yqcm23> Message-ID: <5CBB125D-3D99-458A-9E1A-5B2558625825@gmail.com> On Nov 8, 2011, at 12:52 AM, Romain Tribes wrote: > Hello, > > I'm writing a Risk-like webgame (https://github.com/Sephi-Chan/Conquest-on-Rails) and I want to add tests, but it's painful since objects have a lot of dependencies each other. > > For instance, I have moved the attack logic in a dedicated class (https://github.com/Sephi-Chan/Conquest-on-Rails/blob/develop/app/models/attack.rb) and I would like to test it. > > The problem is that to test an attack, I need to have at least two ownerships (the relation between a territory and a participation). And to have two ownerships, I need to have many participations (the relation between a player and a game), and for that I need players. > > It's a lot of setup for a quite simple test. If it requires a lot of set up it is inherently complex. Even though the premise of the test might feel simple to you, the fact that you have to negotiate your way through a web of dependencies means that when something fails, you'll have a longer trail to hike to find the cause. It also means your code is going to be hard to change. Loose coupling is one hallmark of good, flexible software. Tests that require a lot of setup expose a tightly coupled design. > So, what should I do? Is this a pet project for you, or something for work? If it's the former, something you're using as a learning/practice vehicle, I'd recommend starting over test first, and any time you find that the test is starting to require complex set up, stop and rethink the design. > Should I write a big setup for my suite? Or can I write a "sub-suites" with this big setup? You can always extract big setup to some helper methods that set things up for you. All of us do this more than we'd like to admit. But it always ends up biting you in the end. HTH, David From dchelimsky at gmail.com Mon Nov 14 23:13:18 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 14 Nov 2011 22:13:18 -0600 Subject: [rspec-users] Problem with mocking helper methods In-Reply-To: <14742ccb-41a5-4cfa-91f5-ccba44b02f63@n6g2000vbg.googlegroups.com> References: <14742ccb-41a5-4cfa-91f5-ccba44b02f63@n6g2000vbg.googlegroups.com> Message-ID: On Nov 11, 2011, at 6:48 AM, Ervin wrote: > Given that I assume that rails helper image_tag works as intended, I > want to mock out call to this method in my helper. > > spec/helpers/some_helper_spec.rb: > require 'spec_helper' > describe SomeHelper do > it 'allows stub tags' do > helper.should_receive(:image_tag).with(2).and_return(3) > helper.image_tag(2).should == 3 > end > end Unfortunately, I copied the example (from 'it' to 'end') directly into a helper spec and it passed :( Are there any other testing related gems in your Gemfile that might be gumming things up? > result: > Failure/Error : helper.image_tag(2).should == 3 > expected : 3 > got : "\"2\"" (using ==) > > Bundle: > * rspec (2.7.0) > * rspec-core (2.7.1) > * rspec-expectations (2.7.0) > * rspec-mocks (2.7.0) > * rspec-rails (2.7.0) > * rails (3.1.1) From dchelimsky at gmail.com Mon Nov 14 23:28:17 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 14 Nov 2011 22:28:17 -0600 Subject: [rspec-users] set_fixture_class works on individual test, but test suite fails In-Reply-To: References: Message-ID: On Nov 8, 2011, at 10:52 AM, Stephen Kessler wrote: > Hi all, > > I have a bug in my code that I have been unable to track down that > deals with the set_fixture_class statement. Basically, > set_fixture_class (and my tests) are working fine when I test one > controller in isolation, but they are failing when I run all my > controller specs together. > > My project use both a local database and Amazon Rds, and the tables on > Amazon are namespaced with Rds::TableName. > > My controller spec looks something like: > > describe MyFirstController do > set_fixture_class :users => Rds::User set_fixture_class is defined in rails: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/fixtures.rb#L745 It's a class method that interacts with a class_attribute defined in the same file: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/fixtures.rb#L727 This means that once it's set, it's set, which explains the behavior you're seeing. You can get around this by storing the original setting and restoring it in an after block: before do @orig = self.class.fixture_class_names[:users] self.class.fixture_class_names[:users] = Rds::User end after do self.class.fixture_class_names[:users] = Rds::User end This is very invasive as it interacts directly with variables instead of APIs, so it might easily break in a future version of rails, but I'm not sure what better option you have. It's not really designed to be used how you're using it. HTH, David > describe 'my test' do > it 'should do something' do > joe = users(:joe) > end > end > end > > This works fine when running just this controller's spec. But when I > run all the controller specs, the error I get is: > > Failure/Error: joe = users(:joe) > FixtureClassNotFound: > No class attached to find. > > I have isolated the problem to the interaction between two controller > specs, MyFirstController (which contains set_fixture_class) and > MySecondController (which does not contain set_fixture_class). When > the tests for MyFirstController are run before the tests for > MySecondController, everything works fine. But when the order is > reversed, I get the above errors. > > Any ideas on what I might be able to do to fix this (besides requiring > MyFirstController to run first)? > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users -------------- next part -------------- An HTML attachment was scrubbed... URL: From patrick at collinatorstudios.com Tue Nov 15 00:59:33 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Mon, 14 Nov 2011 21:59:33 -0800 (PST) Subject: [rspec-users] need some advice on the best way to structure testable shared methods In-Reply-To: References: Message-ID: > Use the described class: > > shared_examples "a nameable thingie" do |klass| > describe "#build_name" do > it "it adds the collection of arguments to the base components and formats them for a form element name attribute" do > described_class.new(nil,nil).build_name(:lol, :lollerskates, :roflcopter).should == "lol[lollerskates][roflcopter]" > end > end > end But what happens if the classes do not have the same argument expectations, such as: class Foo include NameBuilder def initialize(arg1) ... end end class Bar include NameBuilder def initialize(arg1, arg2, arg3) ... end end ... In this case, "described_class.new(nil, nil)" is not going to work out very well. Patrick J. Collins http://collinatorstudios.com From jko170 at gmail.com Tue Nov 15 02:49:18 2011 From: jko170 at gmail.com (Justin Ko) Date: Tue, 15 Nov 2011 00:49:18 -0700 Subject: [rspec-users] Testing Custom Methods In-Reply-To: References: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> <520053F0-E38E-46FA-AECE-C3490459AFA9@gmail.com> Message-ID: <435C44DD-7411-4714-A6B4-5484EC3AD9FB@gmail.com> Tony, this text right here is considered "top posting" because it is *above* the previous posts. Now, scroll down and you'll see my "bottom post". On Nov 13, 2011, at 11:03 PM, Tony Spore wrote: > Thanks David. > I am getting a long way now. > -Thanks, > Tony Spore > CEO > SaasSoft LLC > (805) 253-1277 > saassoft.com > > > > > On Sun, Nov 13, 2011 at 4:29 PM, David Chelimsky wrote: > > On Nov 13, 2011, at 4:54 PM, Tony Spore wrote: > >> On Sun, Nov 13, 2011 at 8:12 AM, David Chelimsky wrote: >> On Nov 12, 2011, at 6:27 PM, Tony Spore wrote: >> >>> >>> >>> >>> >>> -Thanks, >>> Tony Spore >>> >>> >>> >>> On Sat, Nov 12, 2011 at 2:14 PM, David Chelimsky wrote: >>> On Nov 12, 2011, at 3:33 PM, Tony Spore wrote: >>> >>>> I am attempting to test a custom method, and totally bombing out. >>>> describe Record do >>>> describe '#save_cf_data' do >>>> before :each do >>>> @record = mock_model(Record) >>> >>> mock_model creates a test double, or pure mock ... >>> >>>> end >>>> it "should have a birthday" do >>>> @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) >>>> @record.birth_day.should eql 3 >>> >>> ... which means that @record here ^^ is a test double, not a Record object ... >>> >>>> end >>>> end >>>> >>>> My Model looks like this: >>>> class Record < ActiveRecord::Base >>>> def save_cf_data(params) >>>> result = params[:final_outputs].first >>>> .... >>>> self.birth_day = result['birth_day'].first >>>> end >>>> end >>> >>> ... which means that this class definition ^^ has nothing to do with anything in the example above. >>> >>>> I have this output - As if I'm not hitting the method correctly - >>>> Mock "Record_1002" received unexpected message :save_cf_data with ({"final_outputs"=>[{"birth_day"=>["3"]}]}) >>>> >>> >>> What you want is either stub_model, or just Record.new or, if you're using something like factory_girl, Factory.build(Record). >>> >>> See https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-model and https://www.relishapp.com/rspec/rspec-rails/docs/mocks/stub-model for more info. >>> >>> HTH, >>> David >> >>> Great thanks! >>> >>> So now I am at least calling the method - But when I try to add in the params that I'm being sent I keep returning nil - >>> Failure/Error: @record.save_cf_data(result) >>> NoMethodError: >>> You have a nil object when you didn't expect it! >>> You might have expected an instance of Array. >>> The error occurred while evaluating nil.delete >>> >>> In the above case I create the hash as result = {"final_outputs"=>["surname"=>["hagan"]]} >>> >>> When I manually place in the params - >>> Failure/Error: @record.save_cf_data({"final_outputs"=>["surname"=>["hagan"]]}) >>> NoMethodError: >>> You have a nil object when you didn't expect it! >>> You might have expected an instance of Array. >>> The error occurred while evaluating nil.first >>> >>> So now as I go down this path, I would say that I am not feeding into the method my params. How would it be best to do that? >>> >>> I am right now just trying to use rspec with no additional params. >>> >>> Thanks again! >> >> I'd love to help, but ... >> >> 1. please post either inline or at the bottom (I moved your post to the bottom in this case - see http://idallen.com/topposting.html). >> 2. please post actual code or a link to a gist instead of descriptions of the code or changes you made. And example is worth 10000 words, and it makes it easier for people who are trying to help to understand exactly what you're dealing with. >> >> Cheers, >> David >> > > Moving your post to the bottom again .... > >> Sorry David, >> I am getting this error: >> ailure/Error: @record.save_cf_data(result) >> NoMethodError: >> You have a nil object when you didn't expect it! >> You might have expected an instance of Array. >> The error occurred while evaluating nil.first >> >> >> Here is my Gist of my code that I can't figure out how to test. - >> https://gist.github.com/1362863 >> >> So I am expecting it to send in my result, but instead the test has nil. > > The spec uses the string key "final_outputs", but the code uses the symbol key :final_outputs. > > HTH, > David > > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users If you can see this, you're looking at a "bottom post". Do *this* for every reply on any mailing list. It makes it easier to follow conversations. Sorry if it seems like I'm coming off as an ass, but David asked you to bottom post 3 times. Just want to make it clear ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: From matt at mattwynne.net Tue Nov 15 06:30:27 2011 From: matt at mattwynne.net (Matt Wynne) Date: Tue, 15 Nov 2011 11:30:27 +0000 Subject: [rspec-users] Write tests for objects with lots of dependencies In-Reply-To: <5CBB125D-3D99-458A-9E1A-5B2558625825@gmail.com> References: <21632501.695.1320735160942.JavaMail.geo-discussion-forums@yqcm23> <5CBB125D-3D99-458A-9E1A-5B2558625825@gmail.com> Message-ID: On 15 Nov 2011, at 04:04, David Chelimsky wrote: > On Nov 8, 2011, at 12:52 AM, Romain Tribes wrote: > >> Hello, >> >> I'm writing a Risk-like webgame (https://github.com/Sephi-Chan/Conquest-on-Rails) and I want to add tests, but it's painful since objects have a lot of dependencies each other. >> >> For instance, I have moved the attack logic in a dedicated class (https://github.com/Sephi-Chan/Conquest-on-Rails/blob/develop/app/models/attack.rb) and I would like to test it. >> >> The problem is that to test an attack, I need to have at least two ownerships (the relation between a territory and a participation). And to have two ownerships, I need to have many participations (the relation between a player and a game), and for that I need players. >> >> It's a lot of setup for a quite simple test. > > If it requires a lot of set up it is inherently complex. Even though the premise of the test might feel simple to you, the fact that you have to negotiate your way through a web of dependencies means that when something fails, you'll have a longer trail to hike to find the cause. It also means your code is going to be hard to change. Loose coupling is one hallmark of good, flexible software. Tests that require a lot of setup expose a tightly coupled design. +1 I'd recommend this book too: http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052 > >> So, what should I do? > > Is this a pet project for you, or something for work? If it's the former, something you're using as a learning/practice vehicle, I'd recommend starting over test first, and any time you find that the test is starting to require complex set up, stop and rethink the design. > >> Should I write a big setup for my suite? Or can I write a "sub-suites" with this big setup? > > You can always extract big setup to some helper methods that set things up for you. All of us do this more than we'd like to admit. But it always ends up biting you in the end. > > HTH, > David > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users cheers, Matt -- Freelance programmer & coach Author, http://pragprog.com/book/hwcuc/the-cucumber-book (with Aslak Helles?y) Founder, http://relishapp.com +44(0)7974430184 | http://twitter.com/mattwynne -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Tue Nov 15 07:18:18 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 15 Nov 2011 06:18:18 -0600 Subject: [rspec-users] need some advice on the best way to structure testable shared methods In-Reply-To: References: Message-ID: On Nov 14, 2011, at 11:59 PM, Patrick J. Collins wrote: >> Use the described class: >> >> shared_examples "a nameable thingie" do |klass| >> describe "#build_name" do >> it "it adds the collection of arguments to the base components and formats them for a form element name attribute" do >> described_class.new(nil,nil).build_name(:lol, :lollerskates, :roflcopter).should == "lol[lollerskates][roflcopter]" >> end >> end >> end > > But what happens if the classes do not have the same argument expectations, > such as: > > class Foo > > include NameBuilder > > def initialize(arg1) > ... > end > > end I misunderstood your initial example, thinking that NameBuilder required an initializer w/ two args. I'd use a factory pattern here: def new_foo(arg1=nil,arg2=nil) Foo.new(arg1,arg2) end def new_bar(arg=nil) Bar.new(arg) end Now you can use these without arguments when you want to: describe Foo do it_behaves_like "a nameable thingie", new_foo end describe Bar do it_behaves_like "a nameable thingie", new_bar end And you can use the with arguments as well: it "does something else" do foo = make_foo(x) other_foo = make_foo(x,y) end David From lists at iDIAcomputing.com Tue Nov 15 08:08:54 2011 From: lists at iDIAcomputing.com (George Dinwiddie) Date: Tue, 15 Nov 2011 08:08:54 -0500 Subject: [rspec-users] Write tests for objects with lots of dependencies In-Reply-To: References: <21632501.695.1320735160942.JavaMail.geo-discussion-forums@yqcm23> <5CBB125D-3D99-458A-9E1A-5B2558625825@gmail.com> Message-ID: <4EC26466.7080401@iDIAcomputing.com> On 11/15/11 6:30 AM, Matt Wynne wrote: > > On 15 Nov 2011, at 04:04, David Chelimsky wrote: > >> On Nov 8, 2011, at 12:52 AM, Romain Tribes wrote: >> >>> Hello, >>> >>> I'm writing a Risk-like webgame >>> (https://github.com/Sephi-Chan/Conquest-on-Rails) and I want to add >>> tests, but it's painful since objects have a lot of dependencies each >>> other. >>> >>> For instance, I have moved the attack logic in a dedicated class >>> (https://github.com/Sephi-Chan/Conquest-on-Rails/blob/develop/app/models/attack.rb) >>> and I would like to test it. >>> >>> The problem is that to test an attack, I need to have at least two >>> ownerships (the relation between a territory and a participation). >>> And to have two ownerships, I need to have many participations (the >>> relation between a player and a game), and for that I need players. >>> >>> It's a lot of setup for a quite simple test. >> >> If it requires a lot of set up it is inherently complex. Even though >> the premise of the test might feel simple to you, the fact that you >> have to negotiate your way through a web of dependencies means that >> when something fails, you'll have a longer trail to hike to find the >> cause. It also means your code is going to be hard to change. Loose >> coupling is one hallmark of good, flexible software. Tests that >> require a lot of setup expose a tightly coupled design. > > +1 > > I'd recommend this book too: > http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052 +2 I'd recommend starting with http://objectmentor.com/resources/articles/dip.pdf as it will help you break those dependency chains. >>> So, what should I do? >> >> Is this a pet project for you, or something for work? If it's the >> former, something you're using as a learning/practice vehicle, I'd >> recommend starting over test first, and any time you find that the >> test is starting to require complex set up, stop and rethink the design. >> >>> Should I write a big setup for my suite? Or can I write a >>> "sub-suites" with this big setup? >> >> You can always extract big setup to some helper methods that set >> things up for you. All of us do this more than we'd like to admit. But >> it always ends up biting you in the end. -- ---------------------------------------------------------------------- * George Dinwiddie * http://blog.gdinwiddie.com Software Development http://www.idiacomputing.com Consultant and Coach http://www.agilemaryland.org ---------------------------------------------------------------------- From tspore at saassoft.com Tue Nov 15 12:17:25 2011 From: tspore at saassoft.com (Tony Spore) Date: Tue, 15 Nov 2011 09:17:25 -0800 Subject: [rspec-users] Testing Custom Methods In-Reply-To: <435C44DD-7411-4714-A6B4-5484EC3AD9FB@gmail.com> References: <70CF9F00-EA87-4A43-90BA-50CDCD306070@gmail.com> <520053F0-E38E-46FA-AECE-C3490459AFA9@gmail.com> <435C44DD-7411-4714-A6B4-5484EC3AD9FB@gmail.com> Message-ID: On Mon, Nov 14, 2011 at 11:49 PM, Justin Ko wrote: > Tony, this text right here is considered "top posting" because it is > *above* the previous posts. Now, scroll down and you'll see my "bottom > post". > > On Nov 13, 2011, at 11:03 PM, Tony Spore wrote: > > Thanks David. > I am getting a long way now. > > -Thanks, > Tony Spore > CEO > SaasSoft LLC > (805) 253-1277 > saassoft.com > > > > On Sun, Nov 13, 2011 at 4:29 PM, David Chelimsky wrote: > >> >> On Nov 13, 2011, at 4:54 PM, Tony Spore wrote: >> >> On Sun, Nov 13, 2011 at 8:12 AM, David Chelimsky wrote: >> >>> On Nov 12, 2011, at 6:27 PM, Tony Spore wrote: >>> >>> >>> >>> >>> >>> >>> -Thanks, >>> Tony Spore >>> >>> >>> On Sat, Nov 12, 2011 at 2:14 PM, David Chelimsky wrote: >>> >>>> On Nov 12, 2011, at 3:33 PM, Tony Spore wrote: >>>> >>>> I am attempting to test a custom method, and totally bombing out. >>>> describe Record do >>>> describe '#save_cf_data' do >>>> before :each do >>>> @record = mock_model(Record) >>>> >>>> >>>> mock_model creates a test double, or pure mock ... >>>> >>>> end >>>> it "should have a birthday" do >>>> @record.save_cf_data({"final_outputs"=>["birth_day"=>["3"]]}) >>>> >>>> @record.birth_day.should eql 3 >>>> >>>> >>>> ... which means that @record here ^^ is a test double, not a Record >>>> object ... >>>> >>>> end >>>> end >>>> >>>> My Model looks like this: >>>> class Record < ActiveRecord::Base >>>> def save_cf_data(params) >>>> result = params[:final_outputs].first >>>> .... >>>> self.birth_day = result['birth_day'].first >>>> end >>>> end >>>> >>>> >>>> ... which means that this class definition ^^ has nothing to do with >>>> anything in the example above. >>>> >>>> I have this output - As if I'm not hitting the method correctly - >>>> >>>> Mock "Record_1002" received unexpected message :save_cf_data with >>>> ({"final_outputs"=>[{"birth_day"=>["3"]}]}) >>>> >>>> >>>> What you want is either stub_model, or just Record.new or, if you're >>>> using something like factory_girl, Factory.build(Record). >>>> >>>> See https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-modeland >>>> https://www.relishapp.com/rspec/rspec-rails/docs/mocks/stub-model for >>>> more info. >>>> >>>> HTH, >>>> David >>>> >>> >>> Great thanks! >>> >>> So now I am at least calling the method - But when I try to add in the >>> params that I'm being sent I keep returning nil - >>> Failure/Error: @record.save_cf_data(result) >>> NoMethodError: >>> You have a nil object when you didn't expect it! >>> You might have expected an instance of Array. >>> The error occurred while evaluating nil.delete >>> >>> In the above case I create the hash as result >>> = {"final_outputs"=>["surname"=>["hagan"]]} >>> >>> When I manually place in the params - >>> Failure/Error: >>> @record.save_cf_data({"final_outputs"=>["surname"=>["hagan"]]}) >>> NoMethodError: >>> You have a nil object when you didn't expect it! >>> You might have expected an instance of Array. >>> The error occurred while evaluating nil.first >>> >>> So now as I go down this path, I would say that I am not feeding into >>> the method my params. How would it be best to do that? >>> >>> I am right now just trying to use rspec with no additional params. >>> >>> Thanks again! >>> >>> >>> I'd love to help, but ... >>> >>> 1. please post either inline or at the bottom (I moved your post to the >>> bottom in this case - see http://idallen.com/topposting.html). >>> 2. please post actual code or a link to a gist instead of descriptions >>> of the code or changes you made. And example is worth 10000 words, and it >>> makes it easier for people who are trying to help to understand exactly >>> what you're dealing with. >>> >>> Cheers, >>> David >>> >>> >> Moving your post to the bottom again .... >> >> Sorry David, >> I am getting this error: >> ailure/Error: @record.save_cf_data(result) >> NoMethodError: >> You have a nil object when you didn't expect it! >> You might have expected an instance of Array. >> The error occurred while evaluating nil.first >> >> >> Here is my Gist of my code that I can't figure out how to test. - >> https://gist.github.com/1362863 >> >> So I am expecting it to send in my result, but instead the test has nil. >> >> The spec uses the string key "final_outputs", but the code uses the >> symbol key :final_outputs. >> HTH, >> David >> >> >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users >> > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > > > If you can see this, you're looking at a "bottom post". Do *this* for > every reply on any mailing list. It makes it easier to follow conversations. > Sorry if it seems like I'm coming off as an ass, but David asked you to > bottom post 3 times. Just want to make it clear ;) > > > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users Ok sorry didn't understand. -------------- next part -------------- An HTML attachment was scrubbed... URL: From patmaddox at me.com Tue Nov 15 20:44:35 2011 From: patmaddox at me.com (Pat Maddox) Date: Tue, 15 Nov 2011 17:44:35 -0800 Subject: [rspec-users] need some advice on the best way to structure testable shared methods In-Reply-To: References: Message-ID: On Nov 14, 2011, at 4:57 PM, Patrick J. Collins wrote: > > Can anyone suggest a better way? Really tough to follow that example, so apologies if I'm off. I use the template method pattern for stuff like this. My shared example group references a method that isn't implemented. Example groups that use that shared example group then define it using let. And of course you can parameterize the shared example groups or pass it a context. See https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples for some examples. Pat From lists at ruby-forum.com Wed Nov 16 12:34:49 2011 From: lists at ruby-forum.com (Vin MR) Date: Wed, 16 Nov 2011 18:34:49 +0100 Subject: [rspec-users] newbie cucumber tutorial In-Reply-To: References: Message-ID: <6e2b4a815fdbfe5e8e346154b4f2f753@ruby-forum.com> I'm new with Ruby and Cucumber. I've tried this simple test, but it didn't work for me Given .... When I enter ABC on keyboard Then ... And here is the ruby code When /^I enter "([^\"]*) on keyboard$/ do |input| ..... end I always get a complain when executing the test "You can implement step definitions for undefined steps with there snippets: When /^I enter ABC on keyboard$/ do pending # express the regexp above with the code you wish you had end " And the code above was not executed. Can anyone tell what I've done wrong here? Thanks. -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Wed Nov 16 12:43:09 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 16 Nov 2011 11:43:09 -0600 Subject: [rspec-users] newbie cucumber tutorial In-Reply-To: <6e2b4a815fdbfe5e8e346154b4f2f753@ruby-forum.com> References: <6e2b4a815fdbfe5e8e346154b4f2f753@ruby-forum.com> Message-ID: <9B32EF88-60AF-41BB-B21C-8ED6B13ED000@gmail.com> On Nov 16, 2011, at 11:34 AM, Vin MR wrote: > I'm new with Ruby and Cucumber. I've tried this simple test, but it > didn't work for me Please send this to the Cucumber mailing list: http://groups.google.com/group/cukes Cheers, David From chabgood at gmail.com Wed Nov 16 12:45:35 2011 From: chabgood at gmail.com (Chris Habgood) Date: Wed, 16 Nov 2011 11:45:35 -0600 Subject: [rspec-users] newbie cucumber tutorial In-Reply-To: <6e2b4a815fdbfe5e8e346154b4f2f753@ruby-forum.com> References: <6e2b4a815fdbfe5e8e346154b4f2f753@ruby-forum.com> Message-ID: this group is for rspec On Wed, Nov 16, 2011 at 11:34, Vin MR wrote: > I'm new with Ruby and Cucumber. I've tried this simple test, but it > didn't work for me > > Given .... > When I enter ABC on keyboard > Then ... > > > And here is the ruby code > When /^I enter "([^\"]*) on keyboard$/ do |input| > ..... > end > > > > I always get a complain when executing the test > "You can implement step definitions for undefined steps with there > snippets: > > When /^I enter ABC on keyboard$/ do > pending # express the regexp above with the code you wish you had > end > " > > And the code above was not executed. > > > Can anyone tell what I've done wrong here? > > Thanks. > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -- *"In matters of style, swim with the current; in matters of principle, stand like a rock." Thomas Jefferson * -------------- next part -------------- An HTML attachment was scrubbed... URL: From aslak.hellesoy at gmail.com Wed Nov 16 12:46:56 2011 From: aslak.hellesoy at gmail.com (aslak hellesoy) Date: Wed, 16 Nov 2011 17:46:56 +0000 Subject: [rspec-users] newbie cucumber tutorial In-Reply-To: <6e2b4a815fdbfe5e8e346154b4f2f753@ruby-forum.com> References: <6e2b4a815fdbfe5e8e346154b4f2f753@ruby-forum.com> Message-ID: On Wed, Nov 16, 2011 at 5:34 PM, Vin MR wrote: > I'm new with Ruby and Cucumber. ?I've tried this simple test, but it > didn't work for me > > Given .... > When I enter ABC on keyboard > Then ... > > > And here is the ruby code > When /^I enter "([^\"]*) on keyboard$/ do |input| That RegExp doesn't match your step. This will match: /^I enter (.*) on keyboard$/ Aslak > ..... > end > > > > I always get a complain when executing the test > "You can implement step definitions for undefined steps with there > snippets: > > When /^I enter ABC on keyboard$/ do > ?pending # express the regexp above with the code you wish you had > end > " > > And the code above was not executed. > > > Can anyone tell what I've done wrong here? > > Thanks. > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From aslak.hellesoy at gmail.com Wed Nov 16 12:48:19 2011 From: aslak.hellesoy at gmail.com (aslak hellesoy) Date: Wed, 16 Nov 2011 17:48:19 +0000 Subject: [rspec-users] newbie cucumber tutorial In-Reply-To: References: <6e2b4a815fdbfe5e8e346154b4f2f753@ruby-forum.com> Message-ID: On Wed, Nov 16, 2011 at 5:45 PM, Chris Habgood wrote: > this group is for rspec > The Cucumber list -> http://groups.google.com/group/cukes > On Wed, Nov 16, 2011 at 11:34, Vin MR wrote: >> >> I'm new with Ruby and Cucumber. ?I've tried this simple test, but it >> didn't work for me >> >> Given .... >> When I enter ABC on keyboard >> Then ... >> >> >> And here is the ruby code >> When /^I enter "([^\"]*) on keyboard$/ do |input| >> ..... >> end >> >> >> >> I always get a complain when executing the test >> "You can implement step definitions for undefined steps with there >> snippets: >> >> When /^I enter ABC on keyboard$/ do >> ?pending # express the regexp above with the code you wish you had >> end >> " >> >> And the code above was not executed. >> >> >> Can anyone tell what I've done wrong here? >> >> Thanks. >> >> -- >> Posted via http://www.ruby-forum.com/. >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users > > > > -- > "In matters of style, swim with the current; in matters of principle, stand > like a rock." > Thomas Jefferson > > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From lists at ruby-forum.com Thu Nov 17 11:52:14 2011 From: lists at ruby-forum.com (Mohnish G j) Date: Thu, 17 Nov 2011 17:52:14 +0100 Subject: [rspec-users] How to access local variable(s) of controller methods called via RSpec in Rails 3 Message-ID: Hi, I'm testing for action caching via RSpec. Currently the method that is cached is in a controller. I'm able to call this method using `subject.send(:method_name)` Thanks to this http://stackoverflow.com/questions/5200326/rspec-testing-calling-controller-method-received-nomethoderror. I want to test a scenario to check if action caching is perfectly working. My test case goes something like this:- **Step 1** : Call the action which is cached. This action has an instance variable which stores queried results of user specific stats like number of users belonging to each of the areas out of a number of areas within a city. I need to fetch the initial set of results some how from the controller to my spec file.( **The question is how do I do that ?**) **Step 2**: Update an area for a single user. This would change the overall stats wrt this area(if it already exists) or would add a new area if its completely unique. **Step 3**: Recall the cached action, and check If I am still able to end up with the old results, not the latest changes as of what was done in step 2; in terms area stats for the users. Now to do this, I need to use the instance variable result as in Step 1, with an instance variable result I obtain after recalling the cached action this very Step. **Step 4**: Finally , comparing both results, they should be same. This would pass my test case. The **BIG** Question again, how do I access the local variable(s) of a controller method in my spec file? Thanks. -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Thu Nov 17 15:22:30 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 17 Nov 2011 14:22:30 -0600 Subject: [rspec-users] How to access local variable(s) of controller methods called via RSpec in Rails 3 In-Reply-To: References: Message-ID: On Nov 17, 2011, at 10:52 AM, Mohnish G j wrote: > Hi, > > I'm testing for action caching via RSpec. Currently the method that is > cached is in a controller. I'm able to call this method using > `subject.send(:method_name)` Thanks to this > http://stackoverflow.com/questions/5200326/rspec-testing-calling-controller-method-received-nomethoderror. > > I want to test a scenario to check if action caching is perfectly > working. My test case goes something like this:- > > **Step 1** : Call the action which is cached. This action has an > instance variable which stores queried results of user specific stats > like number of users belonging to each of the areas out of a number of > areas within a city. I need to fetch the initial set of results some how > from the controller to my spec file.( **The question is how do I do that > ?**) > > **Step 2**: Update an area for a single user. This would change the > overall stats wrt this area(if it already exists) or would add a new > area if its completely unique. > > **Step 3**: Recall the cached action, and check If I am still able to > end up with the old results, not the latest changes as of what was done > in step 2; in terms area stats for the users. Now to do this, I need to > use the instance variable result as in Step 1, with an instance variable > result I obtain after recalling the cached action this very Step. > > **Step 4**: Finally , comparing both results, they should be same. This > would pass my test case. > > The **BIG** Question again, how do I access the local variable(s) of a > controller method in my spec file? You don't need to, so why would you want to? Here's the strategy I use to spec caching, and I think this is pretty common. 1. In a request spec (or integration, if you prefer that naming), write an end to end example that specifies that you repeatedly get the same result. This doesn't say anything about caching, just that the same result comes back twice. This should have no stubbing or mocking. It will be slow, but there's only one of these. 2. In a controller spec, set a message expectation on a model that the query is only requested once, and invoke the controller action twice. e.g. User.should_receive(:in_zipcode).once get :the_action_that_is_being_cached get :the_action_that_is_being_cached That's it! No need to interrogate internals. No need to actually access data. The only thing being mocked is on the surface of the object. Now you probably want to specify how/when the cache expires as well, but that's a different matter. This only covers the caching itself. HTH, David From lists at ruby-forum.com Fri Nov 18 05:42:38 2011 From: lists at ruby-forum.com (Mohnish G j) Date: Fri, 18 Nov 2011 11:42:38 +0100 Subject: [rspec-users] How to access local variable(s) of controller methods called via RSpec in Rails 3 In-Reply-To: References: Message-ID: > Now you probably want to specify how/when the cache expires as well, but > that's a different matter. This only covers the caching itself. > > HTH, > David Thanks David, your inputs were really useful. How do you suggest I can test expiry of cache in this scenario. Are there any common strategies for this too? -- Posted via http://www.ruby-forum.com/. From anexiole at gmail.com Fri Nov 18 06:18:11 2011 From: anexiole at gmail.com (Gordon) Date: Fri, 18 Nov 2011 03:18:11 -0800 (PST) Subject: [rspec-users] What does :count actually mean in assert_select? Message-ID: Hi guys, I tried reading up the RSPEC Book (Dec 2010) and googled a bit but I could not find anything. I'm using Rspec2. Example: spec/factories/categories.rb ====================== FactoryGirl.define do factory :category_intakes, :class => 'category' do name 'intakes and filters' description 'airfilters and etc.' created_by 1 updated_by 1 end factory :category_audio, :class => 'category' do name 'audio' description 'in car entertainment' created_by 1 updated_by 1 end end spec/views/categories/index.html.erb ============================= require 'spec_helper' describe "categories/index.html.erb" do before(:each) do assign( :categories, [ FactoryGirl.create(:category_intakes), FactoryGirl.create(:category_audio), ] ) end it "renders a list of categories" do render assert_select "tr>td", :text => "intakes and filters".to_s, :count => 1 assert_select "tr>td", :text => "audio".to_s, :count => 1 end end I noticed that the index view spec above passes but when I change the count to 2, it fails saying that only 1 element is expected. Question: 1) what does :count actually mean? Does it mean the total number of fixture objects expected? 2) does the ordering of the rendered fixture items matter ( ie. :category_audio is expected before :category_intakes)? From anexiole at gmail.com Fri Nov 18 06:29:23 2011 From: anexiole at gmail.com (Gordon Yeong) Date: Fri, 18 Nov 2011 22:29:23 +1100 Subject: [rspec-users] What does :count actually mean in assert_select? In-Reply-To: References: Message-ID: I think i answered my own question. :count refers to the number of fixture objects. The reason why :count => 2 was passing for views index specs is because 2 objects are being mocked and they are identical. Hence, there are 2 stock tests: 1) asserts that there are 2 elements which have the name of 'Name' 2) asserts that there are 2 elements which have the name of 'Description' This is what a stock view index spec looks like: ---- Stock index spec view ---- describe "makes/index.html.erb" do before(:each) do assign(:makes, [ stub_model(Make, :name => "Name", :description => "Description", :created_by => "", :updated_by => "" ), stub_model(Make, :name => "Name", :description => "Description", :created_by => "", :updated_by => "" ) ]) end it "renders a list of makes" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Name".to_s, :count => 2 # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "tr>td", :text => "Description".to_s, :count => 2 end end ---- Stock index spec view ---- -------------- next part -------------- An HTML attachment was scrubbed... URL: From denise.mauldin at gmail.com Fri Nov 18 19:42:32 2011 From: denise.mauldin at gmail.com (Denise Mauldin) Date: Fri, 18 Nov 2011 16:42:32 -0800 Subject: [rspec-users] How to create stub_models with connections to other models Message-ID: Hello all, Please help with my question, detailed here: http://stackoverflow.com/questions/8002318/ruby-rails-rspec-local-variables Thanks, Denise From patrick at collinatorstudios.com Fri Nov 18 20:42:16 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Fri, 18 Nov 2011 17:42:16 -0800 (PST) Subject: [rspec-users] testing a post to a controller's create action Message-ID: I just spent a lot of time trying to get a test to pass that would not pass no matter what I did, and I finally decided to just do something really simple to verify that even that was working-- and it's not. class PostsController < ApplicationController def create debugger # or binding.pry end end -- #controllers/post_spec.rb describe PostsController do it "does not work" do post :create end end ... I never see the debugger prompt.. Can anyone PLEASE tell me why this is not working? In any other test, binding.pry or debugger interrupts the test flow and gives me access to the current scope of the debugger call. Patrick J. Collins http://collinatorstudios.com From dchelimsky at gmail.com Fri Nov 18 21:18:03 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 18 Nov 2011 20:18:03 -0600 Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: References: Message-ID: On Nov 18, 2011, at 7:42 PM, Patrick J. Collins wrote: > I just spent a lot of time trying to get a test to pass that would not pass no > matter what I did, and I finally decided to just do something really simple to > verify that even that was working-- and it's not. > > class PostsController < ApplicationController > > def create > debugger # or binding.pry > end > > end > > -- > > #controllers/post_spec.rb > > describe PostsController do > > it "does not work" do > post :create > end > > end > > ... > > I never see the debugger prompt.. Can anyone PLEASE tell me why this is not > working? In any other test, binding.pry or debugger interrupts the test flow > and gives me access to the current scope of the debugger call. Got any authentication in front of posts#create? From mmazur at gmail.com Fri Nov 18 23:50:35 2011 From: mmazur at gmail.com (Mike Mazur) Date: Sat, 19 Nov 2011 12:50:35 +0800 Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: References: Message-ID: Hi, On Sat, Nov 19, 2011 at 09:42, Patrick J. Collins wrote: > I just spent a lot of time trying to get a test to pass that would not pass no > matter what I did, and I finally decided to just do something really simple to > verify that even that was working-- and it's not. > > class PostsController < ApplicationController > > ? ? ? ?def create > ? ? ? ? ? ? ? ?debugger # or binding.pry > ? ? ? ?end > > end > > -- > > #controllers/post_spec.rb Shouldn't this be called `spec/controllers/posts_controller_spec.rb`? > describe PostsController do > > ? ? ? ?it "does not work" do > ? ? ? ? ? ? ? ?post :create > ? ? ? ?end > > end > > ... > > I never see the debugger prompt.. ?Can anyone PLEASE tell me why this is not > working? ?In any other test, binding.pry or debugger interrupts the test flow > and gives me access to the current scope of the debugger call. Also as David suggests, perhaps it's a before_filter somewhere sending a response before the request is passed to PostsController#create. Mike From patrick at collinatorstudios.com Sat Nov 19 11:57:00 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Sat, 19 Nov 2011 08:57:00 -0800 (PST) Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: References: Message-ID: > > I never see the debugger prompt.. Can anyone PLEASE tell me why this is not > > working? In any other test, binding.pry or debugger interrupts the test flow > > and gives me access to the current scope of the debugger call. > > Got any authentication in front of posts#create? Yeah, that was the problem! There was authentication in the ApplicationController and so I needed a skip_before_filter... Ok.. Taking this a step forward, what I really am trying to do is write tests that isolate some methods that are called by before_filters in my controller. So, lets say I have something like: class PostsController < ApplicationController before_filter :store_params, :only => :create def create ... create stuff end def store_params session[:post_params] = params[:post] end end What I would like to do is totally isolate store_params... So I'd do something like: describe "#store_params" do it "saves the post params for later" do session[:post_params].should be_blank post :create, { :post => { :fake_param => "foobar" } } session[:post_params][:fake_param].should == "foobar" end end ... Ok this is all groovy, except my tests will fail because fake_param is not an attribute on Post, and when it actually gets to the create method it essentially be trying to do Post.create!(:fake_param => "foobar")... So obviously I could choose to go about this differently and use a real post attribute-- but I am just curious if there is a way to isolate the testing of this method and make #create not even connected in any way? I was thinking originally that I should be able to do (prior to the post create call): PostsController.any_instance.stubs(:create).returns true But that doesn't seem to do anything... Patrick J. Collins http://collinatorstudios.com From jko170 at gmail.com Sat Nov 19 14:40:01 2011 From: jko170 at gmail.com (Justin Ko) Date: Sat, 19 Nov 2011 12:40:01 -0700 Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: References: Message-ID: On Nov 19, 2011, at 9:57 AM, Patrick J. Collins wrote: >>> I never see the debugger prompt.. Can anyone PLEASE tell me why this is not >>> working? In any other test, binding.pry or debugger interrupts the test flow >>> and gives me access to the current scope of the debugger call. >> >> Got any authentication in front of posts#create? > > Yeah, that was the problem! There was authentication in the > ApplicationController and so I needed a skip_before_filter... > > Ok.. Taking this a step forward, what I really am trying to do is write > tests that isolate some methods that are called by before_filters in my > controller. > > So, lets say I have something like: > > class PostsController < ApplicationController > > before_filter :store_params, :only => :create > > def create > ... create stuff > end > > def store_params > session[:post_params] = params[:post] > end > > end > > What I would like to do is totally isolate store_params... So I'd do something > like: > > describe "#store_params" do > it "saves the post params for later" do > session[:post_params].should be_blank > > post :create, { :post => { :fake_param => "foobar" } } > > session[:post_params][:fake_param].should == "foobar" > end > end #store_params is not an "action", therefore I would make it private. Since it is used only by the #create action, I would spec it as part of the #create spec: describe '#create' do it 'stores the :post params' do post :create, { :post => { :fake_param => "foobar" } } session[:post_params][:fake_param].should == "foobar" end end > > ... Ok this is all groovy, except my tests will fail because fake_param is not > an attribute on Post, and when it actually gets to the create method it > essentially be trying to do Post.create!(:fake_param => "foobar")... So > obviously I could choose to go about this differently and use a real post > attribute-- but I am just curious if there is a way to isolate the testing of > this method and make #create not even connected in any way? > > I was thinking originally that I should be able to do (prior to the post create > call): You can, but you should mock Post.create!: describe '#create' do it 'stores the :post params' do Post.should_receive(:create!).and_return(true) post :create, { :post => { :fake_param => "foobar" } } session[:post_params][:fake_param].should == "foobar" end end > > PostsController.any_instance.stubs(:create).returns true > > But that doesn't seem to do anything... > > > Patrick J. Collins > http://collinatorstudios.com > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From patrick at collinatorstudios.com Sat Nov 19 18:03:31 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Sat, 19 Nov 2011 15:03:31 -0800 (PST) Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: References: Message-ID: > #store_params is not an "action", therefore I would make it private. I agree completely, and probably should have specified that in my sample code (it certainly is private in my real non-hypothetical implementation). > Since it is used only by the #create action, I would spec it as part of the #create spec: Well this came up for me because I have a bit of a complex controller which has several before_filters, and I wanted a clean way to really verify that each and every filter is doing what it should, so that's why I wanted to spec those individual methods. > You can, but you should mock Post.create!: > > describe '#create' do > it 'stores the :post params' do > Post.should_receive(:create!).and_return(true) > post :create, { :post => { :fake_param => "foobar" } } > session[:post_params][:fake_param].should == "foobar" > end > end Unfortunately, this project is using a plugin called "Decent Exposure" which does various magic to simplify controller code (and honestly has been a big headache). So, the create action actually calls post.save! the 'post' that .save! is called on is actually auto-generated by a method created by Decent Exposure. It returns a new record pre-populated with params[:post]... The failure I see is: Failure/Error: post :create, { :post => { :fake_param => "foobar" } } ActiveRecord::UnknownAttributeError: unknown attribute: foo # ./app/controllers/posts_controller.rb:107:in `new' ... So, I can't stub out "create!", because this failure is happening before there... And, if I do: Post.stubs(:new).returns(true) I still get the same failure. I even took it a step further where I explicitly told decent exposure to use a method: expose(:post) do exposed_for_post if params[:post] end def exposed_for_post Post.new(params[:post]) end .. And guess what? Doing subject.stubs(:exposed_for_post).returns true still gives me the same failure, unknown attribute: foo in 'new'... But, manually testing stuff proves that exposed_for_post method IS being called, and everything is working.. I just want an automated test to prove it. I am totally stumped on this one... Patrick J. Collins http://collinatorstudios.com From jko170 at gmail.com Sun Nov 20 00:49:13 2011 From: jko170 at gmail.com (Justin Ko) Date: Sat, 19 Nov 2011 22:49:13 -0700 Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: References: Message-ID: <5A590E4B-C5FA-4D48-A0A8-34CC80FDDEBE@gmail.com> On Nov 19, 2011, at 4:03 PM, Patrick J. Collins wrote: >> #store_params is not an "action", therefore I would make it private. > > I agree completely, and probably should have specified that in my sample code > (it certainly is private in my real non-hypothetical implementation). > >> Since it is used only by the #create action, I would spec it as part of the #create spec: > > Well this came up for me because I have a bit of a complex controller which has > several before_filters, and I wanted a clean way to really verify that each and > every filter is doing what it should, so that's why I wanted to spec those > individual methods. > >> You can, but you should mock Post.create!: >> >> describe '#create' do >> it 'stores the :post params' do >> Post.should_receive(:create!).and_return(true) >> post :create, { :post => { :fake_param => "foobar" } } >> session[:post_params][:fake_param].should == "foobar" >> end >> end > > Unfortunately, this project is using a plugin called "Decent Exposure" which > does various magic to simplify controller code (and honestly has been a big > headache). So, the create action actually calls post.save! > > the 'post' that .save! is called on is actually auto-generated by a method > created by Decent Exposure. It returns a new record pre-populated with > params[:post]... > > The failure I see is: > > Failure/Error: post :create, { :post => { :fake_param => "foobar" } } > ActiveRecord::UnknownAttributeError: > unknown attribute: foo > # ./app/controllers/posts_controller.rb:107:in `new' > > > ... So, I can't stub out "create!", because this failure is happening before > there... And, if I do: Post.stubs(:new).returns(true) > > I still get the same failure. > > I even took it a step further where I explicitly told decent exposure to use a > method: > > expose(:post) do > exposed_for_post if params[:post] > end > > def exposed_for_post > Post.new(params[:post]) > end > > .. And guess what? Doing subject.stubs(:exposed_for_post).returns true > > still gives me the same failure, unknown attribute: foo in 'new'... But, > manually testing stuff proves that exposed_for_post method IS being called, and > everything is working.. I just want an automated test to prove it. > > I am totally stumped on this one... > > Patrick J. Collins > http://collinatorstudios.com > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users Please post the backtrace. From patrick at collinatorstudios.com Sun Nov 20 01:14:35 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Sat, 19 Nov 2011 22:14:35 -0800 (PST) Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: <5A590E4B-C5FA-4D48-A0A8-34CC80FDDEBE@gmail.com> References: <5A590E4B-C5FA-4D48-A0A8-34CC80FDDEBE@gmail.com> Message-ID: > Please post the backtrace. Failures: 1) PostsController#store_post_params stores the last post params in the session Failure/Error: post :create, { :submit_action => submit_type.to_s, :post => { :foo => "bar" } } ActiveRecord::UnknownAttributeError: unknown attribute: foo # ./app/controllers/posts_controller.rb:107:in `new' # ./app/controllers/posts_controller.rb:107:in `exposed_for_session' # ./app/controllers/posts_controller.rb:9 # ./app/controllers/posts_controller.rb:37:in `create' # ./spec/controllers/post_spec.rb:6:in `do_post' # ./spec/controllers/post_spec.rb:25 ------------- and exposed_for_session is: def exposed_for_session Post.new(session.delete(:last_post_params)) if session[:last_post_params] end Like I said, I tried stubbing out the new class method on post by doing something like: fake_post = stub('Post', :save => true) Post.stubs(:new).returns(fake_post) But I still get that same failure. Patrick J. Collins http://collinatorstudios.com From jko170 at gmail.com Sun Nov 20 02:58:41 2011 From: jko170 at gmail.com (Justin Ko) Date: Sun, 20 Nov 2011 00:58:41 -0700 Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: References: <5A590E4B-C5FA-4D48-A0A8-34CC80FDDEBE@gmail.com> Message-ID: <4439820D-CF0A-484D-9B76-A9BD1EB4592D@gmail.com> On Nov 19, 2011, at 11:14 PM, Patrick J. Collins wrote: >> Please post the backtrace. > > Failures: > > 1) PostsController#store_post_params stores the last post params in the session > Failure/Error: post :create, { :submit_action => submit_type.to_s, :post => { :foo => "bar" } } > ActiveRecord::UnknownAttributeError: > unknown attribute: foo > # ./app/controllers/posts_controller.rb:107:in `new' > # ./app/controllers/posts_controller.rb:107:in `exposed_for_session' > # ./app/controllers/posts_controller.rb:9 > # ./app/controllers/posts_controller.rb:37:in `create' > # ./spec/controllers/post_spec.rb:6:in `do_post' > # ./spec/controllers/post_spec.rb:25 > > ------------- > > and exposed_for_session is: > > def exposed_for_session > Post.new(session.delete(:last_post_params)) if session[:last_post_params] > end > > Like I said, I tried stubbing out the new class method on post by doing something like: > > fake_post = stub('Post', :save => true) > Post.stubs(:new).returns(fake_post) > > But I still get that same failure. > > Patrick J. Collins > http://collinatorstudios.com > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users I haven't used ActiveRecord in quite awhile (been using MongoDB), but it looks like you cannot instantiate a record with attributes that don't exist. I think you have two options here: 1.) Only use valid attributes in your params. 2.) Add `with` to your stub to exactly match the arguments to `.new`: Post.stubs(:new).with({last_post_params: {foo: 'bar'}}).returns(fake_post) From patrick at collinatorstudios.com Sun Nov 20 03:46:43 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Sun, 20 Nov 2011 00:46:43 -0800 (PST) Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: <4439820D-CF0A-484D-9B76-A9BD1EB4592D@gmail.com> References: <5A590E4B-C5FA-4D48-A0A8-34CC80FDDEBE@gmail.com> <4439820D-CF0A-484D-9B76-A9BD1EB4592D@gmail.com> Message-ID: > I haven't used ActiveRecord in quite awhile (been using MongoDB), but it looks like you cannot instantiate a record with attributes that don't exist. I think you have two options here: > > 1.) Only use valid attributes in your params. > 2.) Add `with` to your stub to exactly match the arguments to `.new`: > Post.stubs(:new).with({last_post_params: {foo: 'bar'}}).returns(fake_post) Yeah.. I originally had tried your 2nd option... Putting an expectation on the arguments sent to new made no difference. I just tried it again to verify, and I still get the same error. Seems so weird to me. Patrick J. Collins http://collinatorstudios.com From dchelimsky at gmail.com Sun Nov 20 07:41:21 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 20 Nov 2011 06:41:21 -0600 Subject: [rspec-users] testing a post to a controller's create action In-Reply-To: References: <5A590E4B-C5FA-4D48-A0A8-34CC80FDDEBE@gmail.com> <4439820D-CF0A-484D-9B76-A9BD1EB4592D@gmail.com> Message-ID: On Nov 20, 2011, at 2:46 AM, Patrick J. Collins wrote: >> I haven't used ActiveRecord in quite awhile (been using MongoDB), but it looks like you cannot instantiate a record with attributes that don't exist. I think you have two options here: >> >> 1.) Only use valid attributes in your params. >> 2.) Add `with` to your stub to exactly match the arguments to `.new`: >> Post.stubs(:new).with({last_post_params: {foo: 'bar'}}).returns(fake_post) > > Yeah.. I originally had tried your 2nd option... Putting an expectation on > the arguments sent to new made no difference. I just tried it again to verify, > and I still get the same error. Seems so weird to me. Then use the first! The potential problem is that the params change and you need to change them here, but you can alleviate that with a method like valid_attributes: describe PostsController do def valid_attributes { :title => "Isolating change" } end describe "#store_params" do it "saves the post params for later" do session[:post_params].should be_blank post :create, { :post => valid_attributes } session[:post_params].should eq(valid_attributes) end end end You could also use FactoryGirl.attributes_for(:post) if you're using that tool. Either way, this removes the need to figure out where to stub what on the model. If you're concerned about the DB call, you could still stub save! but using valid_attributes would get you past the validations that happen before save!. HTH, David From lists at ruby-forum.com Mon Nov 21 06:28:58 2011 From: lists at ruby-forum.com (Mohnish J.) Date: Mon, 21 Nov 2011 12:28:58 +0100 Subject: [rspec-users] How do we test a Rails Model which does not have an equivalent table in the backend using RSpec Message-ID: I have a **Moderator** model which basically queries web site related stat results from other models. An e.g. of displayed stats could be the total number of users belonging to a particular area out of many areas in a city. Limiting the number of such records to a fixed number. For this, the body defined within the Moderator model makes use of an **Area** model. Since the queries are not using anything from the same model, but actually from other models, there wasn't a need for me to have a table migration wrt this model. I basically am now trying to test the defined methods in the Moderator model using Rspec. What I am basically trying to test is that a call to the method should return success, this I am doing through:- subject.send(:method_name) response.should be_success I'm getting a common error for all such defined methods saying that `database_name.table_name does not exist`. Well , this is true but how should is it really making a difference?, and how to get a work around for this to just test a simple use case of calling a method successfully in the above context. Thanks. -- Posted via http://www.ruby-forum.com/. From ckponnappa at gmail.com Mon Nov 21 08:07:58 2011 From: ckponnappa at gmail.com (Sidu Ponnappa) Date: Mon, 21 Nov 2011 18:37:58 +0530 Subject: [rspec-users] How do we test a Rails Model which does not have an equivalent table in the backend using RSpec In-Reply-To: References: Message-ID: > I'm getting a common error for all such defined methods saying that> `database_name.table_name does not exist`. Well , this is true but how> should is it really making a difference?, and how to get a work around> for this to just test a simple use case of calling a method successfully> in the above context. I don't believe this issue has anything to do with RSpec (you'd see the same if you used MiniTest or any other tool). You want to have Moderator be a simple Ruby object, or possibly have it inherit from ActiveModel rather than ActiveRecord. Best, Sidu. http://c42.in http://rubymonk.com From lists at ruby-forum.com Mon Nov 21 21:11:08 2011 From: lists at ruby-forum.com (Mohnish J.) Date: Tue, 22 Nov 2011 03:11:08 +0100 Subject: [rspec-users] How do we test a Rails Model which does not have an equivalent table in the backend using RSpec In-Reply-To: References: Message-ID: Sidu Ponnappa wrote in post #1032900: >> I'm getting a common error for all such defined methods saying that> > `database_name.table_name does not exist`. Well , this is true but how> > should is > it really making a difference?, and how to get a work around> for this > to just > test a simple use case of calling a method successfully> in the above > context. > I don't believe this issue has anything to do with RSpec (you'd see > the same if you used MiniTest or any other tool). > > You want to have Moderator be a simple Ruby object, or possibly have > it inherit from ActiveModel rather than ActiveRecord. > > Best, > Sidu. > http://c42.in > http://rubymonk.com Thanks for your inputs Sidu,I tried replacing ActiveRecord with ActiveModel got the following error:- /home/mohnish/.rvm/gems/ruby-1.9.2-p180/gems/restfulie-1.0.3/lib/restfulie/server/action_controller/patch.rb:2: warning: already initialized constant HTTP_METHODS /home/mohnish/Cognizant/socialtango/app/models/admin_stats.rb:1:in `': uninitialized constant ActiveModel::Base (NameError) Seems like, I will have to look for another workaround.. -- Posted via http://www.ruby-forum.com/. From chadcf at gmail.com Thu Nov 17 18:56:53 2011 From: chadcf at gmail.com (Chad) Date: Thu, 17 Nov 2011 15:56:53 -0800 (PST) Subject: [rspec-users] problems with javascript testing Message-ID: <82f02ae7-1767-46db-97ca-7bdcc08154e3@cc2g2000vbb.googlegroups.com> Hi all, I may be missing something simple here, but I'm having problems with attempting to get a javascript request test going. I'm not sure if this is the correct place to ask but perhaps someone will be able to direct me to the right place if not. The problem I'm having is that in my before(:each) block in the test I create about 60 records (using FactoryGirl) so that I can test filtering/searching data. Here's my code for that: before(:each) do # create records for pagination and filtering @consumers = FactoryGirl.create_list(:user, 50) @providers = FactoryGirl.create_list(:provider, 10) # create and log in with an admin user @user = Factory(:admin) visit log_in_path fill_in "email", :with => @user.EmailAddress fill_in "password", :with => "foobar" click_button "Log in" end So in effect that just populates some data and logs in with an admin user. The problem is, when I run a test with :js => true, I do not see any users in the list. Take the following two tests: it "should show users", :focus => true, :solr => true do visit users_path save_and_open_page page.should have_css('.row') end it "should show users with javascript", :focus => true, :js => true, :solr => true do visit users_path save_and_open_page page.should have_css('.row') end The first one passes, and opens up a saved page showing a nice list of users. The second one fails, and opens up an empty user listing. I've tried with both selenium and capybara-webkit and both exhibit the same result. Any idea why this may be? From evgeni.dzhelyov at gmail.com Tue Nov 22 05:30:48 2011 From: evgeni.dzhelyov at gmail.com (Evgeni Dzhelyov) Date: Tue, 22 Nov 2011 12:30:48 +0200 Subject: [rspec-users] problems with javascript testing In-Reply-To: <82f02ae7-1767-46db-97ca-7bdcc08154e3@cc2g2000vbb.googlegroups.com> References: <82f02ae7-1767-46db-97ca-7bdcc08154e3@cc2g2000vbb.googlegroups.com> Message-ID: If your tests run in db transaction, you will not see the records when using javascript test adapter, like selenium. Refer to the capybara's README how to solve that, if this is the problem. From lists at ruby-forum.com Tue Nov 22 11:10:41 2011 From: lists at ruby-forum.com (Mohnish J.) Date: Tue, 22 Nov 2011 17:10:41 +0100 Subject: [rspec-users] How do we test a Rails Model which does not have an equivalent table in the backend using RSpec In-Reply-To: References: Message-ID: Mohnish J. wrote in post #1033006: > Sidu Ponnappa wrote in post #1032900: >>> I'm getting a common error for all such defined methods saying that> >> `database_name.table_name does not exist`. Well , this is true but how> >> should is >> it really making a difference?, and how to get a work around> for this >> to just >> test a simple use case of calling a method successfully> in the above >> context. >> I don't believe this issue has anything to do with RSpec (you'd see >> the same if you used MiniTest or any other tool). >> >> You want to have Moderator be a simple Ruby object, or possibly have >> it inherit from ActiveModel rather than ActiveRecord. >> >> Best, >> Sidu. >> http://c42.in >> http://rubymonk.com > > Thanks for your inputs Sidu,I tried replacing ActiveRecord with > ActiveModel got the following error:- > > > /home/mohnish/.rvm/gems/ruby-1.9.2-p180/gems/restfulie-1.0.3/lib/restfulie/server/action_controller/patch.rb:2: > warning: already initialized constant HTTP_METHODS > /home/mohnish/Cognizant/socialtango/app/models/admin_stats.rb:1:in ` (required)>': uninitialized constant ActiveModel::Base (NameError) > > > Seems like, I will have to look for another workaround.. Well, The below line code did work for me:- Model_name.method_name.should_not be_nil -- Posted via http://www.ruby-forum.com/. From ash.moran at patchspace.co.uk Tue Nov 22 15:31:19 2011 From: ash.moran at patchspace.co.uk (Ash Moran) Date: Tue, 22 Nov 2011 20:31:19 +0000 Subject: [rspec-users] Rails code reloading in RSpec test environment? Message-ID: Hi I've worked on a couple of Rails 3 apps recently and the test feedback loop is killing me. With no modifications, it takes 15-25 seconds to run a single example. I've avoided Spork so far, but I've tried Spin[1]. Spin shaves a few seconds off but it's still agonising. I've also experimented with multiple Guard groups and other hacks to run isolated code in lib/, but a lot of the code can't be isolated (all the controllers, for example). My last resort is to try and run Rails against an environment with `config.cache_classes = false`. Has anyone tried this (and got it working)? I imagine it would have to run tests over DRb, which I've only used with Spork before. The last mention of "cache_classes" on this list was in 2009, so I thought I'd check before I invested time in it in case there any major obstacles. Any help appreciated Cheers Ash [1] http://jstorimer.github.com/spin/ -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashmoran From apremdas at gmail.com Tue Nov 22 18:52:20 2011 From: apremdas at gmail.com (Andrew Premdas) Date: Tue, 22 Nov 2011 23:52:20 +0000 Subject: [rspec-users] Rails code reloading in RSpec test environment? In-Reply-To: References: Message-ID: On 22 November 2011 20:31, Ash Moran wrote: > Hi > > I've worked on a couple of Rails 3 apps recently and the test feedback loop is killing me. With no modifications, it takes 15-25 seconds to run a single example. I've avoided Spork so far, but I've tried Spin[1]. Spin shaves a few seconds off but it's still agonising. I've also experimented with multiple Guard groups and other hacks to run isolated code in lib/, but a lot of the code can't be isolated (all the controllers, for example). > > My last resort is to try and run Rails against an environment with `config.cache_classes = false`. Has anyone tried this (and got it working)? I imagine it would have to run tests over DRb, which I've only used with Spork before. The last mention of "cache_classes" on this list was in 2009, so I thought I'd check before I invested time in it in case there any major obstacles. > > Any help appreciated > > Cheers > Ash > Use Ruby 1.8.7 its much faster. There is a very good screencast on Destroy All Software that might help also - the one about extracting domain objects (or something like that). HTH Andrew ps > > [1] http://jstorimer.github.com/spin/ > > -- > http://www.patchspace.co.uk/ > http://www.linkedin.com/in/ashmoran > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -- ------------------------ Andrew Premdas blog.andrew.premdas.org From jko170 at gmail.com Tue Nov 22 19:57:32 2011 From: jko170 at gmail.com (Justin Ko) Date: Tue, 22 Nov 2011 17:57:32 -0700 Subject: [rspec-users] Rails code reloading in RSpec test environment? In-Reply-To: References: Message-ID: <4B6478C9-D411-4B52-864F-BC4AFFAC6734@gmail.com> On Nov 22, 2011, at 4:52 PM, Andrew Premdas wrote: > On 22 November 2011 20:31, Ash Moran wrote: >> Hi >> >> I've worked on a couple of Rails 3 apps recently and the test feedback loop is killing me. With no modifications, it takes 15-25 seconds to run a single example. I've avoided Spork so far, but I've tried Spin[1]. Spin shaves a few seconds off but it's still agonising. I've also experimented with multiple Guard groups and other hacks to run isolated code in lib/, but a lot of the code can't be isolated (all the controllers, for example). >> >> My last resort is to try and run Rails against an environment with `config.cache_classes = false`. Has anyone tried this (and got it working)? I imagine it would have to run tests over DRb, which I've only used with Spork before. The last mention of "cache_classes" on this list was in 2009, so I thought I'd check before I invested time in it in case there any major obstacles. >> >> Any help appreciated >> >> Cheers >> Ash >> > Use Ruby 1.8.7 its much faster. There is a very good screencast on > Destroy All Software that might help also - the one about extracting > domain objects (or something like that). Anytime someone suggests using 1.8, a Chinchilla explodes. 1.9.3 has the "slow require" fix - please use that if it is your concern. > > HTH > > Andrew > > ps > > >> >> [1] http://jstorimer.github.com/spin/ >> >> -- >> http://www.patchspace.co.uk/ >> http://www.linkedin.com/in/ashmoran >> >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users >> > > > > -- > ------------------------ > Andrew Premdas > blog.andrew.premdas.org > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From apremdas at gmail.com Wed Nov 23 02:19:55 2011 From: apremdas at gmail.com (Andrew Premdas) Date: Wed, 23 Nov 2011 07:19:55 +0000 Subject: [rspec-users] Rails code reloading in RSpec test environment? In-Reply-To: <4B6478C9-D411-4B52-864F-BC4AFFAC6734@gmail.com> References: <4B6478C9-D411-4B52-864F-BC4AFFAC6734@gmail.com> Message-ID: On 23 November 2011 00:57, Justin Ko wrote: > > On Nov 22, 2011, at 4:52 PM, Andrew Premdas wrote: > >> On 22 November 2011 20:31, Ash Moran wrote: >>> Hi >>> >>> I've worked on a couple of Rails 3 apps recently and the test feedback loop is killing me. With no modifications, it takes 15-25 seconds to run a single example. I've avoided Spork so far, but I've tried Spin[1]. Spin shaves a few seconds off but it's still agonising. I've also experimented with multiple Guard groups and other hacks to run isolated code in lib/, but a lot of the code can't be isolated (all the controllers, for example). >>> >>> My last resort is to try and run Rails against an environment with `config.cache_classes = false`. Has anyone tried this (and got it working)? I imagine it would have to run tests over DRb, which I've only used with Spork before. The last mention of "cache_classes" on this list was in 2009, so I thought I'd check before I invested time in it in case there any major obstacles. >>> >>> Any help appreciated >>> >>> Cheers >>> Ash >>> >> Use Ruby 1.8.7 its much faster. There is a very good screencast on >> Destroy All Software that might help also - the one about extracting >> domain objects (or something like that). > > Anytime someone suggests using 1.8, a Chinchilla explodes. 1.9.3 has the "slow require" fix - please use that if it is your concern. > Yeh I know, but have you actually tried it out and got benchmarks to prove that 1.9.3 is fast enough? I've been trying for the last few weeks to get the rails test cycle going as quickly as possible. I'd like to be using 1.9.x but its just been to slow. I've tried fast_require patches, done lots of googling, used rvm to try different versions etc. etc.. Currently the Rails test cycle is much faster in 1.8.7 - and for me the speed of the test cycle is the most important thing. Using rvm I can always run the app on 1.9.x in CI and production (so long as I create it using 1.8.x). Even using 1.8.7 the time to run a model spec is a couple of seconds, which really is still to slow, but its bearable. As soon as this becomes 4 or 5 seconds then my style of programming has to change, and I don't want that. If you have some uber fast version of 1.9.3 working reliably with Rails 3.1.x and RVM running a single spec on an empty rails project in less than 2 seconds - please point me in that direction with a link to the particular patch/article/whatever. All best Andrew >> >> HTH >> >> Andrew >> >> ps >> >> >>> >>> [1] http://jstorimer.github.com/spin/ >>> >>> -- >>> http://www.patchspace.co.uk/ >>> http://www.linkedin.com/in/ashmoran >>> >>> _______________________________________________ >>> rspec-users mailing list >>> rspec-users at rubyforge.org >>> http://rubyforge.org/mailman/listinfo/rspec-users >>> >> >> >> >> -- >> ------------------------ >> Andrew Premdas >> blog.andrew.premdas.org >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -- ------------------------ Andrew Premdas blog.andrew.premdas.org From ash.moran at patchspace.co.uk Wed Nov 23 05:54:45 2011 From: ash.moran at patchspace.co.uk (Ash Moran) Date: Wed, 23 Nov 2011 10:54:45 +0000 Subject: [rspec-users] Rails code reloading in RSpec test environment? In-Reply-To: References: <4B6478C9-D411-4B52-864F-BC4AFFAC6734@gmail.com> Message-ID: <3AE411DF-BBCC-4302-8E11-39A105E0046B@patchspace.co.uk> On 23 Nov 2011, at 07:19, Andrew Premdas wrote: >>> Use Ruby 1.8.7 its much faster. There is a very good screencast on >>> Destroy All Software that might help also - the one about extracting >>> domain objects (or something like that). >> >> Anytime someone suggests using 1.8, a Chinchilla explodes. 1.9.3 has the "slow require" fix - please use that if it is your concern. > > Yeh I know, but have you actually tried it out and got benchmarks to > prove that 1.9.3 is fast enough? I've been trying for the last few > weeks to get the rails test cycle going as quickly as possible. I'd > like to be using 1.9.x but its just been to slow. My feeling is that using 1.8.7 over 1.9.3 to gain test speed is throwing the baby out with the bathwater. Ruby 1.9 has been around a long time and has useful advantages over 1.8.7. The two key points to me are: - the slow loading time highlights a design problem, not a performance problem: it should not be necessary to load so much code to test a small part of an app (we are limited as to how much we can extract from the Rails framework) - holding back to 1.8.7 will turn the minor tremors from a gradual shift to 1.9.3 into a tectonic quake (I'm guessing chinchillas don't like earthquakes) For these reasons I'm not prepared to compromise the dev environment and rewrite our 1.9 code to work in 1.8.7, so I'll experiment later with turning on code reloading. If that doesn't work I'm not sure what I'll do? Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashmoran From lists at ruby-forum.com Wed Nov 23 10:10:49 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Wed, 23 Nov 2011 16:10:49 +0100 Subject: [rspec-users] cucumber is_admin? testing Message-ID: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> I don't know where to put this post, but theme of this more similar to my issue. I have trite signin system, like this: > ApplicationController: include SessionsHelper private helper_method :current_user def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end > SessionsHelper: def is_admin? @current_user && @current_user.id == 1 end > features/support/env.rb: World(SessionsHelper) So, if I test > is_admin?.should be_true it returns: expected nil to be true (RSpec::Expectations::ExpectationNotMetError) ./features/step_definitions/users/add_user.rb:23:in `/^I should signin$/' features/users/add_user.feature:13:in `And I should signin' But I signed in! Why? What's the way to test authentication system from scratch? -- Posted via http://www.ruby-forum.com/. From aslak.hellesoy at gmail.com Wed Nov 23 10:22:05 2011 From: aslak.hellesoy at gmail.com (aslak hellesoy) Date: Wed, 23 Nov 2011 15:22:05 +0000 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: On Wed, Nov 23, 2011 at 3:10 PM, Alex Whiteland wrote: > I don't know where to put this post, Here: http://groups.google.com/group/cukes > but theme of this more similar to > my issue. > > I have trite signin system, like this: > >> ApplicationController: > include SessionsHelper > > private > > helper_method :current_user > > def current_user > ?@current_user ||= User.find(session[:user_id]) if session[:user_id] > end > > >> SessionsHelper: > ?def is_admin? > ? @current_user && @current_user.id == 1 > ?end > > >> features/support/env.rb: > World(SessionsHelper) > > So, if I test >> is_admin?.should be_true > > it returns: > > expected nil to be true (RSpec::Expectations::ExpectationNotMetError) > ? ? ?./features/step_definitions/users/add_user.rb:23:in `/^I should > signin$/' > ? ? ?features/users/add_user.feature:13:in `And I should signin' > > But I signed in! Why? What's the way to test authentication system from > scratch? > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From patrick at collinatorstudios.com Wed Nov 23 11:06:10 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Wed, 23 Nov 2011 08:06:10 -0800 (PST) Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: > I don't know where to put this post, but theme of this more similar to > my issue. The cucumber mailing list is: http://groups.google.com/group/cukes But I can tell you that your problem is a scope issue. Your is_admin? method that is added to cucumber's world does not have access to your application controller's @current_user variable. Patrick J. Collins http://collinatorstudios.com From lists at ruby-forum.com Wed Nov 23 11:19:00 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Wed, 23 Nov 2011 17:19:00 +0100 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: <977a5b8690321cb641ae9b9b44c50da4@ruby-forum.com> Aslak, but if I haven't Google Account? -- Posted via http://www.ruby-forum.com/. From aslak.hellesoy at gmail.com Wed Nov 23 12:25:57 2011 From: aslak.hellesoy at gmail.com (aslak hellesoy) Date: Wed, 23 Nov 2011 17:25:57 +0000 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <977a5b8690321cb641ae9b9b44c50da4@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> <977a5b8690321cb641ae9b9b44c50da4@ruby-forum.com> Message-ID: On Wed, Nov 23, 2011 at 4:19 PM, Alex Whiteland wrote: > Aslak, but if I haven't Google Account? > You don't need one. Click "About this group", and you'll see the group's email address. Your first message will be moderated. Aslak > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From lists at ruby-forum.com Wed Nov 23 12:55:04 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Wed, 23 Nov 2011 18:55:04 +0100 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: <0e37f6ee7aa7eab0112dca8d128c80d2@ruby-forum.com> > that is added to cucumber's world does not have access to your > application > controller's @current_user variable. So, I understand this. But how I can avoid this defect? If I paste def is_admin? into application_controller near current_user method, I wouldn't can World(ApplicationController). If I copy current_user code to sessions_helper, then session[:user_id] wouldn't work. -- Posted via http://www.ruby-forum.com/. From apremdas at gmail.com Wed Nov 23 12:53:29 2011 From: apremdas at gmail.com (Andrew Premdas) Date: Wed, 23 Nov 2011 17:53:29 +0000 Subject: [rspec-users] Rails code reloading in RSpec test environment? In-Reply-To: <3AE411DF-BBCC-4302-8E11-39A105E0046B@patchspace.co.uk> References: <4B6478C9-D411-4B52-864F-BC4AFFAC6734@gmail.com> <3AE411DF-BBCC-4302-8E11-39A105E0046B@patchspace.co.uk> Message-ID: On 23 November 2011 10:54, Ash Moran wrote: > > On 23 Nov 2011, at 07:19, Andrew Premdas wrote: > >>>> Use Ruby 1.8.7 its much faster. There is a very good screencast on >>>> Destroy All Software that might help also - the one about extracting >>>> domain objects (or something like that). >>> >>> Anytime someone suggests using 1.8, a Chinchilla explodes. 1.9.3 has the "slow require" fix - please use that if it is your concern. >> >> Yeh I know, but have you actually tried it out and got benchmarks to >> prove that 1.9.3 is fast enough? I've been trying for the last few >> weeks to get the rails test cycle going as quickly as possible. I'd >> like to be using 1.9.x but its just been to slow. > > My feeling is that using 1.8.7 over 1.9.3 to gain test speed is throwing the baby out with the bathwater. Ruby 1.9 has been around a long time and has useful advantages over 1.8.7. The two key points to me are: > > - the slow loading time highlights a design problem, not a performance problem: it should not be necessary to load so much code to test a small part of an app (we are limited as to how much we can extract from the Rails framework) > > - holding back to 1.8.7 will turn the minor tremors from a gradual shift to 1.9.3 into a tectonic quake (I'm guessing chinchillas don't like earthquakes) > > For these reasons I'm not prepared to compromise the dev environment and rewrite our 1.9 code to work in 1.8.7, so I'll experiment later with turning on code reloading. If that doesn't work I'm not sure what I'll do? > > Ash > Fair enough, good luck, and do let us know if you make progress with it. I'd love it if we could find away to make 1.9.x faster for this task All best Andrew > -- > http://www.patchspace.co.uk/ > http://www.linkedin.com/in/ashmoran > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -- ------------------------ Andrew Premdas blog.andrew.premdas.org From aslak.hellesoy at gmail.com Wed Nov 23 14:21:52 2011 From: aslak.hellesoy at gmail.com (aslak hellesoy) Date: Wed, 23 Nov 2011 19:21:52 +0000 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <0e37f6ee7aa7eab0112dca8d128c80d2@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> <0e37f6ee7aa7eab0112dca8d128c80d2@ruby-forum.com> Message-ID: On Wed, Nov 23, 2011 at 5:55 PM, Alex Whiteland wrote: >> that is added to cucumber's world does not have access to your >> application >> controller's @current_user variable. > > So, I understand this. But how I can avoid this defect? > > If I paste def is_admin? into application_controller near current_user > method, I wouldn't can World(ApplicationController). If I copy > current_user ?code to sessions_helper, then session[:user_id] wouldn't > work. > Please don't have this discussion here. You're on the wrong list. Use the Cucumber list. > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From patrick at collinatorstudios.com Wed Nov 23 16:33:42 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Wed, 23 Nov 2011 13:33:42 -0800 (PST) Subject: [rspec-users] test for "lambda {...}.should change(x, y).by(z)" failing.. ? Message-ID: I wrote a test that looked like this: it "increases the user's reputation" do lambda { @comment.update_attribute(:helpful, true) }.should change(@seller.reload, :reputation_score).by(Event.reputation_change_for(:mark_helpful)) end And I am getting this error: 1) Comment comments on posts marking a comment as helpful increases the user's reputation Failure/Error: lambda { @comment.update_attribute(:helpful, true) }.should change(@seller.reload, :reputation_score).by(Event.reputation_change_for(:mark_helpful)) reputation_score should have been changed by 3, but was changed by 0 -- The way the actual code works is, I have a comment observer that does: def after_update(comment) Event.create_for_user(comment.user, :mark_helpful) end And event.rb does something like: def create_for_user(user, event_type) create!(:user => user, :reputation_change => Event::SCORES[event_type]) end The user model has an before_save callback which does: def sum_points self.reputation_score = events.sum(:reputation_change) self.points = events.sum(:points_change) end --- Anyway, so this test fails, and I am not sure why... If I write it in a slightly less-cool way: it "increases the user's reputation" do @seller.reputation_score.should == 0 @comment.update_attribute(:helpful, true) @seller.reload.reputation_score.should == Event.reputation_change_for(:mark_helpful) end Then it passes... If I throw in a debugger statement in there and manually call the code, the reputation_score does indeed increase...... So I am confused why the lambda {}.change thing isn't working? Thanks. Patrick J. Collins http://collinatorstudios.com From jason.nah at gmail.com Wed Nov 23 17:50:58 2011 From: jason.nah at gmail.com (Jason Nah) Date: Thu, 24 Nov 2011 09:50:58 +1100 Subject: [rspec-users] Rails code reloading in RSpec test environment? In-Reply-To: References: Message-ID: <-5284110217324695418@unknownmsgid> What's wrong with using spork? Works well for me. The issue I've found is rails loading everything. So the only 'simple fix' is the spork kind (ie process fork) Cheers, Jason On 23/11/2011, at 7:46 AM, Ash Moran wrote: > Hi > > I've worked on a couple of Rails 3 apps recently and the test feedback loop is killing me. With no modifications, it takes 15-25 seconds to run a single example. I've avoided Spork so far, but I've tried Spin[1]. Spin shaves a few seconds off but it's still agonising. I've also experimented with multiple Guard groups and other hacks to run isolated code in lib/, but a lot of the code can't be isolated (all the controllers, for example). > > My last resort is to try and run Rails against an environment with `config.cache_classes = false`. Has anyone tried this (and got it working)? I imagine it would have to run tests over DRb, which I've only used with Spork before. The last mention of "cache_classes" on this list was in 2009, so I thought I'd check before I invested time in it in case there any major obstacles. > > Any help appreciated > > Cheers > Ash > > > [1] http://jstorimer.github.com/spin/ > > -- > http://www.patchspace.co.uk/ > http://www.linkedin.com/in/ashmoran > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From 08to09 at gmail.com Thu Nov 24 01:48:49 2011 From: 08to09 at gmail.com (Anran Yang) Date: Thu, 24 Nov 2011 14:48:49 +0800 Subject: [rspec-users] customize description and failure messages when writing rspec matcher dsl In-Reply-To: References: Message-ID: Dear all, I recently tried to write a custom matcher using rspec dsl, which I'd like to use as the following: ==========hpgc_spec.rb=================== require "spec_helper" describe Hpgc do specify do should be_structured_as( { :app => { :has => [ :name, :author, :org, :version, :abstract, :uri ], :can_be_a => { :dataset => { :can_be_a => { :vector => {}, :raster => {} } }, :program => { :has => [ :language, :parallel_programming_model, :parallel_performance_overview, :category ] } }, :has_many => { :app_option => { :has => [ :switch, :description ] }, :app_io => { :has => [ :name, :description, :is_in ] } } }}) end end =========================================== The purpose is to test the entire model structure(attributes, inheritance and association). Then I wrote following code to implement it: ========be_structured_as.rb=================== # This is a matcher for test hpgc model structure RSpec::Matchers.define :be_structured_as do |structure| def check(namespace, klass, desc) (desc[:has_many] ||= {}).keys.each { |item| klass.to_s.camelize.constantize.new.should have_many item.to_s.pluralize.to_sym } if !desc[:can_be_a] || desc[:can_be_a].empty? obj = Factory.create(klass) obj.should have_these_attributes (desc[:has] ||= []) else desc[:can_be_a].keys.map { |sub| sub.to_s }.should == namespace.subclasses_of(klass.to_s) desc[:can_be_a].each { |key, value| check namespace, key, value } end end match do |namespace| self.class.send :include, namespace structure.each { |key, value| check namespace, key, value } end end =============================================== To simplify the matcher definition, I used some other machers like "obj.should have_these_attributes (desc[:has] ||= [])", this works fine, thanks to the excellent new matcher dsl syntax. Howerver, I got trouble when running the test using "rspec spec/models/hpgc_spec.rb -fd". The test passed but print [image: Screenshot.png] instead of something like "Hpgc should be structured as ...". I think it may due to the other matcher I used because the message is from the matcher "have_these_attributes". I try to add method "description" but seems it doesn't work. And the failure message is also a problem. I search the web and come across some solutions, but all of them need manually build the message. I've not come out a clean way to do this(I must add some invasive clauses to track the error) and think maybe the best behaviour would be that it "throw" the failure message of inner matchers or false-value expressions. But this time it just told me something like "Hpgc is expected to be structured as ...". Any idea? Best Regards, YANG Anran -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/png Size: 5244 bytes Desc: not available URL: From lists at ruby-forum.com Thu Nov 24 06:12:57 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Thu, 24 Nov 2011 12:12:57 +0100 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: <16421334875a625fb6a0b50b29061c1b@ruby-forum.com> Aslak, I send a message to group email, but I haven't answer yet. -- Posted via http://www.ruby-forum.com/. From aslak.hellesoy at gmail.com Thu Nov 24 06:33:23 2011 From: aslak.hellesoy at gmail.com (aslak hellesoy) Date: Thu, 24 Nov 2011 11:33:23 +0000 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <16421334875a625fb6a0b50b29061c1b@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> <16421334875a625fb6a0b50b29061c1b@ruby-forum.com> Message-ID: On Thu, Nov 24, 2011 at 11:12 AM, Alex Whiteland wrote: > Aslak, I send a message to group email, but I haven't answer yet. > What email did you send to? We haven't received anything from you. I'm assuming you're using a regular mail client? > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From dchelimsky at gmail.com Thu Nov 24 09:24:18 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 24 Nov 2011 08:24:18 -0600 Subject: [rspec-users] customize description and failure messages when writing rspec matcher dsl In-Reply-To: References: Message-ID: <8F2A1497-6CCD-4DA1-96DD-E156887C43E8@gmail.com> On Nov 24, 2011, at 12:48 AM, Anran Yang wrote: > Dear all, > > I recently tried to write a custom matcher using rspec dsl, which I'd like to use as the following: > > ==========hpgc_spec.rb=================== > > require "spec_helper" > > describe Hpgc do > specify do > should be_structured_as( > { :app => { > :has => [ > :name, > :author, > :org, > :version, > :abstract, > :uri > ], > > :can_be_a => { > :dataset => { > :can_be_a => { > :vector => {}, > :raster => {} > } > }, > > :program => { > :has => [ > :language, > :parallel_programming_model, > :parallel_performance_overview, > :category > ] > } > }, > > :has_many => { > :app_option => { > :has => [ > :switch, > :description > ] > }, > > :app_io => { > :has => [ > :name, > :description, > :is_in > ] > } > } > }}) > end > end > > =========================================== > > The purpose is to test the entire model structure(attributes, inheritance and association). Then term Behavior Driven Development came into being, in part, to discourage this approach to testing. We believe testing should be about behavior, and that testing structures leads to highly coupled tests that are hard to change. I'd recommend thinking about the need for each of these attributes, come up with examples of how they are used and write those instead. That said, see below for more on how matchers work. > Then I wrote following code to implement it: > > ========be_structured_as.rb=================== > > # This is a matcher for test hpgc model structure > > RSpec::Matchers.define :be_structured_as do |structure| > def check(namespace, klass, desc) > (desc[:has_many] ||= {}).keys.each { |item| klass.to_s.camelize.constantize.new.should have_many item.to_s.pluralize.to_sym } > if !desc[:can_be_a] || desc[:can_be_a].empty? > obj = Factory.create(klass) > obj.should have_these_attributes (desc[:has] ||= []) > else > desc[:can_be_a].keys.map { |sub| sub.to_s }.should == namespace.subclasses_of(klass.to_s) > desc[:can_be_a].each { |key, value| check namespace, key, value } > end > end > > match do |namespace| > self.class.send :include, namespace > structure.each { |key, value| check namespace, key, value } > end > end > > =============================================== > > To simplify the matcher definition, I used some other machers like "obj.should have_these_attributes (desc[:has] ||= [])", this works fine, thanks to the excellent new matcher dsl syntax. Howerver, I got trouble when running the test using "rspec spec/models/hpgc_spec.rb -fd". The test passed but print > > > > instead of something like "Hpgc should be structured as ...". I think it may due to the other matcher I used because the message is from the matcher "have_these_attributes". That's correct. The default behavior is that the block passed to the "match" method in the matcher DSL is expected to return a boolean. If it raises an exception instead, that exception bubbles up and becomes the source of the failure message. > I try to add method "description" but seems it doesn't work. "description" is used for the documentation formatter, not for failure messages. If you run "rspec spec --format documentation" you'll see names for all your examples. > And the failure message is also a problem. I search the web and come across some solutions, but all of them need manually build the message. I've not come out a clean way to do this(I must add some invasive clauses to track the error) and think maybe the best behaviour would be that it "throw" the failure message of inner matchers or false-value expressions. But this time it just told me something like "Hpgc is expected to be structured as ...". Instead of using the "match" method in the matcher, you can use "match_unless_raises", which returns false if it captures an exception, letting the matcher control the failure message (which is what I think you're looking for): RSpec::Matchers.define :be_structured_as do |structure| def check(namespace, klass, desc) # .... end match_unless_raises do |namespace| self.class.send :include, namespace structure.each { |key, value| check namespace, key, value } end end HTH, David > Any idea? > > Best Regards, > > YANG Anran From lists at ruby-forum.com Thu Nov 24 11:32:55 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Thu, 24 Nov 2011 17:32:55 +0100 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: <8456514c74127f3c47fdcb09040f20b4@ruby-forum.com> > What email did you send to? cukes at googlegroups.com > I'm assuming you're using a regular mail client? I work from browser. I sent to you from awhiteland.37.com (first . replace to @) -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Thu Nov 24 13:21:07 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 24 Nov 2011 12:21:07 -0600 Subject: [rspec-users] test for "lambda {...}.should change(x, y).by(z)" failing.. ? In-Reply-To: References: Message-ID: <5CA3AB11-6C58-45F2-BC50-1AA2D3CDB217@gmail.com> On Nov 23, 2011, at 3:33 PM, Patrick J. Collins wrote: > I wrote a test that looked like this: > > it "increases the user's reputation" do > lambda { @comment.update_attribute(:helpful, true) }.should change(@seller.reload, :reputation_score).by(Event.reputation_change_for(:mark_helpful)) The change matcher has several forms, including: lambda { ... }.should change(object, method).by(amount) lambda { ... }.should change { object.method }.by(amount) Your example uses the former, which results in the following (roughly): receiver = @seller.reload value_before = receiver.reputation_score { @comment.update_attribute(:helpful, true) }.call value_after = receiver.reputation_score (value_after - value_before).should eq(Event.reputation_change_for(:mark_helpful)) As you can see, @seller.reload is only evaluated once, and its reputation score is going to be the same both times. If you want @seller.reload eval'd before and after, then you have to use the block form: lambda { @comment.update_attribute(:helpful, true) }. should change {@seller.reload.reputation_score }. by(Event.reputation_change_for(:mark_helpful)) Tangent: this is testing two things - @seller.reputation_score and Event.reputation_change_for(:mark_helpful). If either is failing to work correctly, this example won't tell you which. I'd recommend sticking to literals in expectations: lambda { @comment.update_attribute(:helpful, true) }. should change {@seller.reload.reputation_score }.by(3) HTH, David > end > > And I am getting this error: > 1) Comment comments on posts marking a comment as helpful increases the user's reputation > Failure/Error: lambda { @comment.update_attribute(:helpful, true) }.should change(@seller.reload, :reputation_score).by(Event.reputation_change_for(:mark_helpful)) > reputation_score should have been changed by 3, but was changed by 0 > > -- > > The way the actual code works is, I have a comment observer that does: > > def after_update(comment) > Event.create_for_user(comment.user, :mark_helpful) > end > > And event.rb does something like: > > def create_for_user(user, event_type) > create!(:user => user, :reputation_change => Event::SCORES[event_type]) > end > > The user model has an before_save callback which does: > > def sum_points > self.reputation_score = events.sum(:reputation_change) > self.points = events.sum(:points_change) > end > > > --- > > Anyway, so this test fails, and I am not sure why... If I write it in a > slightly less-cool way: > > it "increases the user's reputation" do > @seller.reputation_score.should == 0 > @comment.update_attribute(:helpful, true) > @seller.reload.reputation_score.should == Event.reputation_change_for(:mark_helpful) > end > > Then it passes... If I throw in a debugger statement in there and manually > call the code, the reputation_score does indeed increase...... So I am > confused why the lambda {}.change thing isn't working? > > Thanks. > > Patrick J. Collins > http://collinatorstudios.com From marko at renderedtext.com Thu Nov 24 15:38:24 2011 From: marko at renderedtext.com (Marko Anastasov) Date: Thu, 24 Nov 2011 21:38:24 +0100 Subject: [rspec-users] rake spec aborted, how to debug Message-ID: Hello, I'm having an issue running specs on a Rails project. Here's how bundle exec rake spec --trace ends at a random point after some seconds of hanging with a high CPU usage: https://gist.github.com/1392208 I say "a random point" because I can run the problematic spec alone without problems, and if I delete its content and run the entire suite again the error will happen during another spec's example. Given that doesn't change, it always repeats on the same example though. My setup is Ubuntu 10.04 on a Mac VirtualBox, bundler 1.0.18. Other people in my team have the same setup (but not entirely the same ruby patch level version etc), and do not have this issue. I'd very much appreciate any hint how to solve this. From patrick at collinatorstudios.com Thu Nov 24 15:50:18 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Thu, 24 Nov 2011 12:50:18 -0800 (PST) Subject: [rspec-users] test for "lambda {...}.should change(x, y).by(z)" failing.. ? In-Reply-To: <5CA3AB11-6C58-45F2-BC50-1AA2D3CDB217@gmail.com> References: <5CA3AB11-6C58-45F2-BC50-1AA2D3CDB217@gmail.com> Message-ID: > As you can see, @seller.reload is only evaluated once, and its reputation > score is going to be the same both times. Aha.. Makes perfect sense. Thanks. > Tangent: this is testing two things - @seller.reputation_score and > Event.reputation_change_for(:mark_helpful). If either is failing to work > correctly, this example won't tell you which. I'd recommend sticking to > literals in expectations: > > lambda { @comment.update_attribute(:helpful, true) }. should change > {@seller.reload.reputation_score }.by(3) Hmmm.. I totally get why you say this, but part of me really hates the idea of that 3 someday changing to 5 and then my test breaking, forcing me to update the 3 in multiple places. Would it not be safe to assume that if there's a test for Event.rb verifying the behavior of Event.reputation_change_for, then it's safe to use that in a example? When I originally wrote this, I wanted to stub out the Event::SCORES constant and return a hash with just something like: { :mark_helpful => { :reputation_change => 123 } } But I couldn't figure out how to stub a constant..... Of course I could just make my test overwrite the mark helpful value of that constant like: Event:SCORES[:mark_helpful] = { :reputation_change => 123 } But that felt a little wrong so I chose to just rely on a class convenience method to return the constant's value. Any thoughts on these other approaches? Patrick J. Collins http://collinatorstudios.com From zhiqiang.lei at gmail.com Fri Nov 25 09:04:08 2011 From: zhiqiang.lei at gmail.com (Zhi-Qiang Lei) Date: Fri, 25 Nov 2011 22:04:08 +0800 Subject: [rspec-users] before(:all) leaves records in database Message-ID: Hi, When I test my Rails controller, I find that records created in before(:all) remain in database while records created in before(:each) and let are wiped out after testing. This made me run "rake test:prepare" for every new test. Is that normal? Best regards, Zhi-Qiang Lei zhiqiang.lei at gmail.com From evgeni.dzhelyov at gmail.com Fri Nov 25 10:34:27 2011 From: evgeni.dzhelyov at gmail.com (Evgeni Dzhelyov) Date: Fri, 25 Nov 2011 17:34:27 +0200 Subject: [rspec-users] before(:all) leaves records in database In-Reply-To: References: Message-ID: Yes, Only before :each is run in transaction. You should avoid creating records in the before :all hook From dchelimsky at gmail.com Fri Nov 25 11:14:46 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 25 Nov 2011 10:14:46 -0600 Subject: [rspec-users] before(:all) leaves records in database In-Reply-To: References: Message-ID: On Nov 25, 2011, at 8:04 AM, Zhi-Qiang Lei wrote: > Hi, > > When I test my Rails controller, I find that records created in before(:all) remain in database while records created in before(:each) and let are wiped out after testing. This made me run "rake test:prepare" for every new test. Is that normal? Yes. before(:all) is not run in a transaction. From cnk at ugcs.caltech.edu Sat Nov 26 15:38:37 2011 From: cnk at ugcs.caltech.edu (Cynthia Kiser) Date: Sat, 26 Nov 2011 12:38:37 -0800 Subject: [rspec-users] oddness with messages_path Message-ID: <20111126203837.GA9437@ugcs.caltech.edu> I am working through the Rails Views chapter in the RSpec Book and noticed something odd when I created a spec for the edit view. I am getting the wrong value from the messages_path helper. I was kind of wondering if it would work or not - but had expected it to fail by not giving me an id, not by constructing the url incorrectly. With the code below I get the follwing error message. I get the same error when using "messages_path(message)" or "messages_path(message.id)". 1) messages/edit.html.erb renders in update form using the rails way of doing RESTFUL urls Failure/Error: rendered.should have_selector("form", :method => "post", :action => messages_path(message)) expected following output to contain a
      tag: I can work around it by constructing the url myself with "/messages/#{message.id}" but I am curious where the period is coming from in the constructed url. require 'spec_helper' describe 'messages/edit.html.erb' do let(:message) do mock_model("Message", :title => "Existing title", :text => "Existing text") end before(:each) do assign(:message, message) end it "renders in update form using the rails way of doing RESTFUL urls" do render rendered.should have_selector("form", :method => "post", :action => messages_path(message)) rendered.should have_selector("input", :type => "hidden", :name => "_method", :value => "put") end end -- Cynthia N. Kiser cnk at ugcs.caltech.edu From dchelimsky at gmail.com Sat Nov 26 16:37:46 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 26 Nov 2011 15:37:46 -0600 Subject: [rspec-users] oddness with messages_path In-Reply-To: <20111126203837.GA9437@ugcs.caltech.edu> References: <20111126203837.GA9437@ugcs.caltech.edu> Message-ID: On Nov 26, 2011, at 2:38 PM, Cynthia Kiser wrote: > I am working through the Rails Views chapter in the RSpec Book and > noticed something odd when I created a spec for the edit view. I am > getting the wrong value from the messages_path helper. I was kind of > wondering if it would work or not - but had expected it to fail by not > giving me an id, not by constructing the url incorrectly. With the > code below I get the follwing error message. I get the same error > when using "messages_path(message)" or "messages_path(message.id)". > > 1) messages/edit.html.erb renders in update form using the rails way > of doing RESTFUL urls > Failure/Error: rendered.should have_selector("form", :method => > "post", :action => messages_path(message)) > expected following output to contain a action='/messages.1001'/> tag: > > I can work around it by constructing the url myself with > "/messages/#{message.id}" but I am curious where the period is coming > from in the constructed url. > > require 'spec_helper' > > describe 'messages/edit.html.erb' do > let(:message) do > mock_model("Message", :title => "Existing title", :text => "Existing text") > end > > before(:each) do > assign(:message, message) > end > > it "renders in update form using the rails way of doing RESTFUL urls" do > render > rendered.should have_selector("form", :method => "post", > :action => messages_path(message)) > rendered.should have_selector("input", :type => "hidden", > :name => "_method", :value => "put") > end > end What versions of rspec and rails are you using? From patrick at collinatorstudios.com Sat Nov 26 17:21:52 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Sat, 26 Nov 2011 14:21:52 -0800 (PST) Subject: [rspec-users] oddness with messages_path In-Reply-To: <20111126203837.GA9437@ugcs.caltech.edu> References: <20111126203837.GA9437@ugcs.caltech.edu> Message-ID: > I can work around it by constructing the url myself with > "/messages/#{message.id}" but I am curious where the period is coming > from in the constructed url. It's because you should be using a singular resource name to signify that you are updating an existing record. I believe you want to do "message_path(message)" instead of "messages_path(message)" Patrick J. Collins http://collinatorstudios.com From cnk at ugcs.caltech.edu Sat Nov 26 22:03:53 2011 From: cnk at ugcs.caltech.edu (Cynthia Kiser) Date: Sat, 26 Nov 2011 19:03:53 -0800 Subject: [rspec-users] oddness with messages_path In-Reply-To: References: <20111126203837.GA9437@ugcs.caltech.edu> Message-ID: <20111127030353.GA17232@ugcs.caltech.edu> Quoting Patrick J. Collins : > > I can work around it by constructing the url myself with > > "/messages/#{message.id}" but I am curious where the period is coming > > from in the constructed url. > > It's because you should be using a singular resource name to signify that you > are updating an existing record. I believe you want to do > "message_path(message)" instead of "messages_path(message)" D'ho! Exactly right. I am still mystified by the way in which this fails but the problem is indeed that I needed to use message_path. That works with (message) and with (message.id). And this is Rails 3.1.3 and rspec 2.7.0, rspec-core 2.7.1, and rspec-rails 2.7.0. -- Cynthia N. Kiser cnk at ugcs.caltech.edu From jko170 at gmail.com Sat Nov 26 22:33:48 2011 From: jko170 at gmail.com (Justin Ko) Date: Sat, 26 Nov 2011 20:33:48 -0700 Subject: [rspec-users] oddness with messages_path In-Reply-To: <20111127030353.GA17232@ugcs.caltech.edu> References: <20111126203837.GA9437@ugcs.caltech.edu> <20111127030353.GA17232@ugcs.caltech.edu> Message-ID: <2DF27231-4DB4-425C-BA76-744BA7DB5403@gmail.com> On Nov 26, 2011, at 8:03 PM, Cynthia Kiser wrote: > Quoting Patrick J. Collins : >>> I can work around it by constructing the url myself with >>> "/messages/#{message.id}" but I am curious where the period is coming >>> from in the constructed url. >> >> It's because you should be using a singular resource name to signify that you >> are updating an existing record. I believe you want to do >> "message_path(message)" instead of "messages_path(message)" > > D'ho! Exactly right. I am still mystified by the way in which this > fails but the problem is indeed that I needed to use > message_path. That works with (message) and with (message.id). Run "rake routes" and you'll see what the two "paths" generate. > > And this is Rails 3.1.3 and rspec 2.7.0, rspec-core 2.7.1, and > rspec-rails 2.7.0. > -- > Cynthia N. Kiser > cnk at ugcs.caltech.edu > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From cnk at ugcs.caltech.edu Sun Nov 27 01:15:18 2011 From: cnk at ugcs.caltech.edu (Cynthia Kiser) Date: Sat, 26 Nov 2011 22:15:18 -0800 Subject: [rspec-users] oddness with messages_path In-Reply-To: <2DF27231-4DB4-425C-BA76-744BA7DB5403@gmail.com> References: <20111126203837.GA9437@ugcs.caltech.edu> <20111127030353.GA17232@ugcs.caltech.edu> <2DF27231-4DB4-425C-BA76-744BA7DB5403@gmail.com> Message-ID: <20111127061518.GA7824@ugcs.caltech.edu> Quoting Justin Ko : > Run "rake routes" and you'll see what the two "paths" generate. Rake routes didn't really give me much insight - but playing around in the console did. Any argument to messages_path gets interpreted as a format - even an integer. > app.messages_path(:pdf) => "/messages.pdf" > app.messages_path("doc") => "/messages.doc" > app.messages_path(1) => "/messages.1" That hadn't occured to me - even once someone pointed out my singular/plural problem. -- Cynthia N. Kiser cnk at ugcs.caltech.edu From 08to09 at gmail.com Sun Nov 27 08:22:06 2011 From: 08to09 at gmail.com (Anran Yang) Date: Sun, 27 Nov 2011 21:22:06 +0800 Subject: [rspec-users] customize description and failure messages when writing rspec matcher dsl Message-ID: On Nov 24, 2011, at 12:48 AM, Anran Yang wrote: > Dear all, > > I recently tried to write a custom matcher using rspec dsl, which I'd like to use as the following: > > ==========hpgc_spec.rb=================== > > require "spec_helper" > > describe Hpgc do > specify do > should be_structured_as( > { :app => { > :has => [ > :name, > :author, > :org, > :version, > :abstract, > :uri > ], > > :can_be_a => { > :dataset => { > :can_be_a => { > :vector => {}, > :raster => {} > } > }, > > :program => { > :has => [ > :language, > :parallel_programming_model, > :parallel_performance_overview, > :category > ] > } > }, > > :has_many => { > :app_option => { > :has => [ > :switch, > :description > ] > }, > > :app_io => { > :has => [ > :name, > :description, > :is_in > ] > } > } > }}) > end > end > > =========================================== > > The purpose is to test the entire model structure(attributes, inheritance and association). Then term Behavior Driven Development came into being, in part, to discourage this approach to testing. We believe testing should be about behavior, and that testing structures leads to highly coupled tests that are hard to change. I'd recommend thinking about the need for each of these attributes, come up with examples of how they are used and write those instead. That said, see below for more on how matchers work. --------------------------------- It made me thinking a while. But at last I found that I've thought about it, though it may only happen unconsciously. So below is why I need this kind of spec. I must admit the Spec is against BDD's spirit. However, I think BDD may not be enough for all kinds of projects in all kinds of circumstance. In my project, the model itself is also a product, not only the "surface" of the software. Maybe the best way to accomplish this is to separate this kind of test and the "real" BDD test. But rspec can support them perfectly so I'm lazy this time. Maybe there are some other projects involved in this kind of situation? I mean, some projects with a concrete domain model, so to some extent the development is driven by both behavior and knowledge? > Then I wrote following code to implement it: > > ========be_structured_as.rb=================== > > # This is a matcher for test hpgc model structure > > RSpec::Matchers.define :be_structured_as do |structure| > def check(namespace, klass, desc) > (desc[:has_many] ||= {}).keys.each { |item| klass.to_s.camelize.constantize.new.should have_many item.to_s.pluralize.to_sym } > if !desc[:can_be_a] || desc[:can_be_a].empty? > obj = Factory.create(klass) > obj.should have_these_attributes (desc[:has] ||= []) > else > desc[:can_be_a].keys.map { |sub| sub.to_s }.should == namespace.subclasses_of(klass.to_s) > desc[:can_be_a].each { |key, value| check namespace, key, value } > end > end > > match do |namespace| > self.class.send :include, namespace > structure.each { |key, value| check namespace, key, value } > end > end > > =============================================== > > To simplify the matcher definition, I used some other machers like "obj.should have_these_attributes (desc[:has] ||= [])", this works fine, thanks to the excellent new matcher dsl syntax. Howerver, I got trouble when running the test using "rspec spec/models/hpgc_spec.rb -fd". The test passed but print > > > > instead of something like "Hpgc should be structured as ...". I think it may due to the other matcher I used because the message is from the matcher "have_these_attributes". That's correct. The default behavior is that the block passed to the "match" method in the matcher DSL is expected to return a boolean. If it raises an exception instead, that exception bubbles up and becomes the source of the failure message. > I try to add method "description" but seems it doesn't work. "description" is used for the documentation formatter, not for failure messages. If you run "rspec spec --format documentation" you'll see names for all your examples. -------------------------- Maybe I failed express my problem clearly, but the question is for pass message, not failure message. Knowing how rspec raise exception help little to get my spec say "Hpgc should be structured as... " when it passes. The method "description" failed to present itself even when the spec passed, as long as there is an inner "should" clause. > And the failure message is also a problem. I search the web and come across some solutions, but all of them need manually build the message. I've not come out a clean way to do this(I must add some invasive clauses to track the error) and think maybe the best behaviour would be that it "throw" the failure message of inner matchers or false-value expressions. But this time it just told me something like "Hpgc is expected to be structured as ...". Instead of using the "match" method in the matcher, you can use "match_unless_raises", which returns false if it captures an exception, letting the matcher control the failure message (which is what I think you're looking for): RSpec::Matchers.define :be_structured_as do |structure| def check(namespace, klass, desc) # .... end match_unless_raises do |namespace| self.class.send :include, namespace structure.each { |key, value| check namespace, key, value } end end HTH, David ---------------------------------------------------------------- Is the method in rspec-expectation? I searched the local doc but didn't find it. Also I don't quite understand how the method can help track the failing message. It return false, but I still cannot figure out which line fails, isn't it? Thank you for your inspiring reply and tolerance to my poor English :-) Regards, YANG > Any idea? > > Best Regards, > > YANG Anran -------------- next part -------------- An HTML attachment was scrubbed... URL: From thibaut.barrere at gmail.com Sun Nov 27 09:06:37 2011 From: thibaut.barrere at gmail.com (=?UTF-8?Q?Thibaut_Barr=C3=A8re?=) Date: Sun, 27 Nov 2011 06:06:37 -0800 (PST) Subject: [rspec-users] Wrong number of arguments (reduce, rspec/core/metadata) In-Reply-To: <3E3F4489-76B4-414B-976D-6083282AF757@gmail.com> References: <14899485.422.1320770706406.JavaMail.geo-discussion-forums@vbbdd1> <3E3F4489-76B4-414B-976D-6083282AF757@gmail.com> Message-ID: <6659434.591.1322402797443.JavaMail.geo-discussion-forums@yqny18> Hi David, reduce has a number of different forms, one of which is collection.reduce { > ... } (with a block but no args). > My best guess is either your app or another lib/gem is redefining reduce. > Possible? > well I don't know the codebase enough yet, but I guess yes, it's definitely possible. Thanks for the hint! (and sorry for the late reply - as I was newly subscribed to this group, I didn't get your reply until I came back myself on the group). -- Thibaut -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Sun Nov 27 12:43:47 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 27 Nov 2011 11:43:47 -0600 Subject: [rspec-users] customize description and failure messages when writing rspec matcher dsl In-Reply-To: References: Message-ID: <07D628AC-887A-4FC1-876A-CDAF90BA0225@gmail.com> On Nov 27, 2011, at 7:22 AM, Anran Yang wrote: > On Nov 24, 2011, at 12:48 AM, Anran Yang wrote: > > > Dear all, > > > > I recently tried to write a custom matcher using rspec dsl, which I'd like to use as the following: > > > > ==========hpgc_spec.rb=================== > > > > require "spec_helper" > > > > describe Hpgc do > > specify do > > should be_structured_as( > > { :app => { > > :has => [ > > :name, > > :author, > > :org, > > :version, > > :abstract, > > :uri > > ], > > > > :can_be_a => { > > :dataset => { > > :can_be_a => { > > :vector => {}, > > :raster => {} > > } > > }, > > > > :program => { > > :has => [ > > :language, > > :parallel_programming_model, > > :parallel_performance_overview, > > :category > > ] > > } > > }, > > > > :has_many => { > > :app_option => { > > :has => [ > > :switch, > > :description > > ] > > }, > > > > :app_io => { > > :has => [ > > :name, > > :description, > > :is_in > > ] > > } > > } > > }}) > > end > > end > > > > =========================================== > > > > The purpose is to test the entire model structure(attributes, inheritance and association). > > Then term Behavior Driven Development came into being, in part, to discourage this approach to testing. We believe testing should be about behavior, and that testing structures leads to highly coupled tests that are hard to change. > > I'd recommend thinking about the need for each of these attributes, come up with examples of how they are used and write those instead. That said, see below for more on how matchers work. > > --------------------------------- > It made me thinking a while. But at last I found that I've thought about it, though it may only happen unconsciously. So below is why I need this kind of spec. > I must admit the Spec is against BDD's spirit. However, I think BDD may not be enough for all kinds of projects in all kinds of circumstance. In my project, the model itself is also a product, not only the "surface" of the software. Maybe the best way to accomplish this is to separate this kind of test and the "real" BDD test. But rspec can support them perfectly so I'm lazy this time. > Maybe there are some other projects involved in this kind of situation? I mean, some projects with a concrete domain model, so to some extent the development is driven by both behavior and knowledge? The specific problem is that tests about structure are more highly coupled to structure than behavior, and therefore more brittle. This is true whether you wrote the test first or wrote it after, and regardless of what methodology you are thinking of when you write the tests. I don't understand what you mean when you say 'In my project, the model itself is also a product, not only the "surface" of the software.'. Can you elaborate? > > Then I wrote following code to implement it: > > > > ========be_structured_as.rb=================== > > > > # This is a matcher for test hpgc model structure > > > > RSpec::Matchers.define :be_structured_as do |structure| > > def check(namespace, klass, desc) > > (desc[:has_many] ||= {}).keys.each { |item| klass.to_s.camelize.constantize.new.should have_many item.to_s.pluralize.to_sym } > > if !desc[:can_be_a] || desc[:can_be_a].empty? > > obj = Factory.create(klass) > > obj.should have_these_attributes (desc[:has] ||= []) > > else > > desc[:can_be_a].keys.map { |sub| sub.to_s }.should == namespace.subclasses_of(klass.to_s) > > desc[:can_be_a].each { |key, value| check namespace, key, value } > > end > > end > > > > match do |namespace| > > self.class.send :include, namespace > > structure.each { |key, value| check namespace, key, value } > > end > > end > > > > =============================================== > > > > To simplify the matcher definition, I used some other machers like "obj.should have_these_attributes (desc[:has] ||= [])", this works fine, thanks to the excellent new matcher dsl syntax. Howerver, I got trouble when running the test using "rspec spec/models/hpgc_spec.rb -fd". The test passed but print > > > > > > > > instead of something like "Hpgc should be structured as ...". I think it may due to the other matcher I used because the message is from the matcher "have_these_attributes". > > That's correct. The default behavior is that the block passed to the "match" method in the matcher DSL is expected to return a boolean. If it raises an exception instead, that exception bubbles up and becomes the source of the failure message. > > > I try to add method "description" but seems it doesn't work. > > "description" is used for the documentation formatter, not for failure messages. If you run "rspec spec --format documentation" you'll see names for all your examples. > > -------------------------- > Maybe I failed express my problem clearly, but the question is for pass message, not failure message. Knowing how rspec raise exception help little to get my spec say "Hpgc should be structured as... " when it passes. The method "description" failed to present itself even when the spec passed, as long as there is an inner "should" clause. You can define your own description method in the same way: description do |actual| # .... end > > And the failure message is also a problem. I search the web and come across some solutions, but all of them need manually build the message. I've not come out a clean way to do this(I must add some invasive clauses to track the error) and think maybe the best behaviour would be that it "throw" the failure message of inner matchers or false-value expressions. But this time it just told me something like "Hpgc is expected to be structured as ...". > > Instead of using the "match" method in the matcher, you can use "match_unless_raises", which returns false if it captures an exception, letting the matcher control the failure message (which is what I think you're looking for): > > RSpec::Matchers.define :be_structured_as do |structure| > def check(namespace, klass, desc) > # .... > end > > match_unless_raises do |namespace| > self.class.send :include, namespace > structure.each { |key, value| check namespace, key, value } > end > end > > HTH, > David > > > ---------------------------------------------------------------- > Is the method in rspec-expectation? I searched the local doc but didn't find it. It is in rspec-expectations but it is not documented. I added it to support matchers in rspec-rails that delegate to minitest assertions (which raise their own exception), and never took the time to formalize it as a public API. That said, it should be considered public, will not change without appropriate warning, and will be documented in the rdoc for the 2.8 release. > Also I don't quite understand how the method can help track the failing message. It return false, but I still cannot figure out which line fails, isn't it? It stores the exception from the failure in an instance variable named @rescued_exception, which you can access through a method named rescued_exception e.g. failure_messsage_for_should do |actual| "Expected .... but something happened\n#{rescued_exception.message}\n#{rescued_exception.backtrace}" end Another approach would be to keep track of each thing individually using the standard matches method: match do |actual| @reasons == [] @reasons << "no foo" unless foo @reasons << "no bar" unless bar @reasons << "no baz" unless baz @reasons.empty? end That returns false if any conditions fail, but doesn't raise an exceptions. Then you can use @reasons in the failure message, e.g. failure_message_for_should do |actual| "Failed because #{@reasons.join(', ')}" end > Thank you for your inspiring reply and tolerance to my poor English :-) Your English is perfectly understandable. Cheers, David > Regards, > YANG > > > Any idea? > > > > Best Regards, > > > > YANG Anran From lists at ruby-forum.com Sun Nov 27 14:24:24 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Sun, 27 Nov 2011 20:24:24 +0100 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: <5b0493ba5587e9de380c4cae76128878@ruby-forum.com> bump! I sent letter 3 day ago. No email answer, no new theme in group, no new message here. But new message in group exists. Why? -- Posted via http://www.ruby-forum.com/. From ash.moran at patchspace.co.uk Sun Nov 27 16:41:40 2011 From: ash.moran at patchspace.co.uk (Ash Moran) Date: Sun, 27 Nov 2011 21:41:40 +0000 Subject: [rspec-users] Skipping slow specs in Guard but running them from that file In-Reply-To: <20110830134537.GB3208@erisiandiscord.de> References: <20110830060127.GA3208@erisiandiscord.de> <97DA81BD-A160-4EA8-A437-C7BCD1642557@patchspace.co.uk> <20110830134537.GB3208@erisiandiscord.de> Message-ID: On 30 Aug 2011, at 14:45, Nikolay Sturm wrote: > * Ash Moran [2011-08-30]: >> I never thought of that! Yes, that could also work, probably better in >> fact. It just involves running multiple Guard processes, although >> there's Terminitor[1] for that! > > A single guard process is enough, it will start all guards defined in > your Guardfile. Hi Nikolay Just reviving this old thread as I ran into problems with multiple RSpec guards[1] (patched now). Have you ever seen this behaviour? I forgot to write an acceptance test so as yet nobody believes me it happens :) Ash [1] https://github.com/guard/guard-rspec/issues/74 -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashmoran From aslak.hellesoy at gmail.com Mon Nov 28 05:35:40 2011 From: aslak.hellesoy at gmail.com (=?UTF-8?Q?Aslak_Helles=C3=B8y?=) Date: Mon, 28 Nov 2011 18:35:40 +0800 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <5b0493ba5587e9de380c4cae76128878@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> <5b0493ba5587e9de380c4cae76128878@ruby-forum.com> Message-ID: <451015680074551591@unknownmsgid> On Nov 28, 2011, at 4:46, Alex Whiteland wrote: > bump! > > I sent letter 3 day ago. > > No email answer, no new theme in group, no new message here. But new > message in group exists. Why? > I haven't seen any messages from you to cukes at googlegroups.com Do you have a link to it? > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From apremdas at gmail.com Mon Nov 28 09:45:21 2011 From: apremdas at gmail.com (Andrew Premdas) Date: Mon, 28 Nov 2011 14:45:21 +0000 Subject: [rspec-users] oddness with messages_path In-Reply-To: <20111127061518.GA7824@ugcs.caltech.edu> References: <20111126203837.GA9437@ugcs.caltech.edu> <20111127030353.GA17232@ugcs.caltech.edu> <2DF27231-4DB4-425C-BA76-744BA7DB5403@gmail.com> <20111127061518.GA7824@ugcs.caltech.edu> Message-ID: On 27 November 2011 06:15, Cynthia Kiser wrote: > Quoting Justin Ko : >> Run "rake routes" and you'll see what the two "paths" generate. > > Rake routes didn't really give me much insight - but playing around in > the console did. Any argument to messages_path gets interpreted as a > format - even an integer. > > ?> app.messages_path(:pdf) > ?=> "/messages.pdf" > ?> app.messages_path("doc") > ?=> "/messages.doc" > ?> app.messages_path(1) > ?=> "/messages.1" > > That hadn't occured to me - even once someone pointed out my > singular/plural problem. > Because you were running a singular route the parameter you were passing was matching the :format part of the route. So what you were doing was telling the routing that instead of html you wanted your message (which resolves to the id of the message). So instead of xxx.html you are getting xxx.1 or whatever the id is. Rake routes tells you this: Singular resource - resource :users, :only => :show users GET /users(.:format) Plural resource - resources :users, :only => :show user GET /users/:id(.:format) # you can pass an id to this route You can see that with the singular resource passing an :id to the users_path makes no sense, as the route can't understand it. HTH Andrew > -- > Cynthia N. Kiser > cnk at ugcs.caltech.edu > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -- ------------------------ Andrew Premdas blog.andrew.premdas.org From lists at ruby-forum.com Mon Nov 28 10:38:13 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Mon, 28 Nov 2011 16:38:13 +0100 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: <8578b8541928551f245ab33ccc57ec04@ruby-forum.com> wtf? maybe I post an initiate letter here, and then find a way to write you? > Started here Hi! I have trite signin system, like this: > ApplicationController: include SessionsHelper private helper_method :current_user def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end > SessionsHelper: def is_admin? @current_user && @current_user.id == 1 end > features/support/env.rb: World(SessionsHelper) So, if I test > is_admin?.should be_true it returns: expected nil to be true (RSpec::Expectations::ExpectationNotMetError) ./features/step_definitions/users/add_user.rb:23:in `/^I should signin$/' features/users/add_user.feature:13:in `And I should signin' But I signed in! Why? What's the way to test authentication system from scratch? > that is added to cucumber's world does not have access to your > application > controller's @current_user variable. So, I understand this. But how I can avoid this defect? If I paste def is_admin? into application_controller near current_user method, I wouldn't can World(ApplicationController). If I copy current_user code to sessions_helper, then session[:user_id] wouldn't work. Regards, Alex Whiteland > end -- Posted via http://www.ruby-forum.com/. From lists at ruby-forum.com Mon Nov 28 10:48:00 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Mon, 28 Nov 2011 16:48:00 +0100 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: I sent copy of my issue to cukes at googlegroups.com from awhiteland at hushmail.com -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Mon Nov 28 11:10:01 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 28 Nov 2011 10:10:01 -0600 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <8578b8541928551f245ab33ccc57ec04@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> <8578b8541928551f245ab33ccc57ec04@ruby-forum.com> Message-ID: On Mon, Nov 28, 2011 at 9:38 AM, Alex Whiteland wrote: > wtf? > > maybe I post an initiate letter here, and then find a way to write you? > >> Started here > Hi! > > I have trite signin system, like this: > >> ApplicationController: > include SessionsHelper > > private > > helper_method :current_user > > def current_user > ?@current_user ||= User.find(session[:user_id]) if session[:user_id] > end > > >> SessionsHelper: > ?def is_admin? > ? @current_user && @current_user.id == 1 > ?end > > >> features/support/env.rb: > World(SessionsHelper) > > So, if I test >> is_admin?.should be_true > > it returns: > > expected nil to be true (RSpec::Expectations::ExpectationNotMetError) > ? ? ?./features/step_definitions/users/add_user.rb:23:in `/^I should > signin$/' > ? ? ?features/users/add_user.feature:13:in `And I should signin' > > But I signed in! Why? What's the way to test authentication system from > scratch? > >> that is added to cucumber's world does not have access to your >> application >> controller's @current_user variable. > > So, I understand this. But how I can avoid this defect? It is not a defect. It's how cukes work. They wrap Rails integration tests, which don't give you direct access to controllers or sessions. Your options are: 1. actually log in (i.e. create a user, go to the login screen and log in). You can wrap this in a single step definition like "Given I am logged in as 'admin'", but you still have to go through the app within the step definition. 2. This only works for in-memory scenarios (i.e. it doesn't work in-browser when the app is running in a separate process) - you _can_ stub the controller using any_instance: FooController.any_instance.stub(:current_user).and_return(user) HTH, David > > If I paste def is_admin? into application_controller near current_user > method, I wouldn't can World(ApplicationController). If I copy > current_user ?code to sessions_helper, then session[:user_id] wouldn't > work. > > Regards, Alex Whiteland >> end > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From lists at ruby-forum.com Mon Nov 28 23:07:44 2011 From: lists at ruby-forum.com (Alex Whiteland) Date: Tue, 29 Nov 2011 05:07:44 +0100 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> Message-ID: <0cd9deb3bffa34f4302d59a4b87e507b@ruby-forum.com> > 1. actually log in (i.e. create a user, go to the login screen and log > in). You can wrap this in a single step definition like "Given I am > logged in as 'admin'", but you still have to go through the app within > the step definition. I do this. Here is example: Scenario: guest becomes a user Given I am guest When I go to the signup_path And puts signup info Then new user should be created And I should signin > Smth. Given /^I am guest$/ do get_me_the_cookies.should eq([]) end When /^I go to the signup_path$/ do visit signup_path end When /^puts signup info$/ do fill_in "user_username", :with => "frankpopp" fill_in "user_first", :with => "Frank" fill_in "user_second", :with => "Popp" fill_in "user_password", :with => "123456" fill_in "user_password_confirmation", :with => "123456" click_button "Sign up!" end Then /^new user should be created$/ do page.should have_content("New user added: frankpopp") end Then /^I should signin$/ do is_user?.should be_true end > in users_controller.rb: def create @user = User.new(params[:user]) if @user.save session[:user_id] = @user.id # This create a session flash[:success] = "New user added: " + @user.username flash[:notice] = "His password is: " + @user.password if is_admin? redirect_to @user else end end -- Posted via http://www.ruby-forum.com/. From ash.moran at patchspace.co.uk Tue Nov 29 04:55:21 2011 From: ash.moran at patchspace.co.uk (Ash Moran) Date: Tue, 29 Nov 2011 09:55:21 +0000 Subject: [rspec-users] Write tests for objects with lots of dependencies In-Reply-To: <21632501.695.1320735160942.JavaMail.geo-discussion-forums@yqcm23> References: <21632501.695.1320735160942.JavaMail.geo-discussion-forums@yqcm23> Message-ID: On 8 Nov 2011, at 06:52, Romain Tribes wrote: > I'm writing a Risk-like webgame (https://github.com/Sephi-Chan/Conquest-on-Rails) and I want to add tests, but it's painful since objects have a lot of dependencies each other. Hi Romain I was just catching up on some old RSpec emails and found this. I had a quick look through your code and noticed you have model specs but not controller specs. What led you to skip writing specs for the controllers? I'm just curious to see if there are common reasons for doing this (I think it's not uncommon). Cheers Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashmoran From dchelimsky at gmail.com Tue Nov 29 05:24:04 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 29 Nov 2011 04:24:04 -0600 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: <0cd9deb3bffa34f4302d59a4b87e507b@ruby-forum.com> References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> <0cd9deb3bffa34f4302d59a4b87e507b@ruby-forum.com> Message-ID: On Nov 28, 2011, at 10:07 PM, Alex Whiteland wrote: >> 1. actually log in (i.e. create a user, go to the login screen and log >> in). You can wrap this in a single step definition like "Given I am >> logged in as 'admin'", but you still have to go through the app within >> the step definition. > I do this. Here is example: > > Scenario: guest becomes a user > Given I am guest > When I go to the signup_path > And puts signup info > Then new user should be created > And I should signin > >> Smth. > > Given /^I am guest$/ do > get_me_the_cookies.should eq([]) > end ^^ Givens, by definition, are given; to be taken for granted. They should not have expectations in them. If you feel the need to have an expectation in them, it suggests that there is another sceneario missing. > When /^I go to the signup_path$/ do > visit signup_path > end > > When /^puts signup info$/ do > fill_in "user_username", :with => "frankpopp" > fill_in "user_first", :with => "Frank" > fill_in "user_second", :with => "Popp" > fill_in "user_password", :with => "123456" > fill_in "user_password_confirmation", :with => "123456" > click_button "Sign up!" > end > > Then /^new user should be created$/ do > page.should have_content("New user added: frankpopp") > end This doesn't tell you that the new user actually exists. Here I'd recommend going to the database: Then /^new user should be created$/ do User.find_by_username("frankpopp").should_not be_nil end > Then /^I should signin$/ do > is_user?.should be_true > end Your email earlier this thread has an "is_admin?" method, so I'll assume "is_user?" works the same way: def is_admin? @current_user && @current_user.id != 1 end The problem is that @current_user is an instance variable inside the controller. You can't access it from a scenario. Usually I just use something something on the page to identify that "frankpopp" is signed in. >> in users_controller.rb: > def create > @user = User.new(params[:user]) > if @user.save > session[:user_id] = @user.id # This create a session > flash[:success] = "New user added: " + @user.username > flash[:notice] = "His password is: " + @user.password if is_admin? > redirect_to @user > else > > end > end HTH, David From dchelimsky at gmail.com Tue Nov 29 05:29:14 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 29 Nov 2011 04:29:14 -0600 Subject: [rspec-users] cucumber is_admin? testing In-Reply-To: References: <201a8df12f34c8d36a46c0979314f1e7@ruby-forum.com> <0cd9deb3bffa34f4302d59a4b87e507b@ruby-forum.com> Message-ID: <91C14133-D6D4-463F-B42D-5A0AC0BCCB90@gmail.com> On Nov 29, 2011, at 4:24 AM, David Chelimsky wrote: > > On Nov 28, 2011, at 10:07 PM, Alex Whiteland wrote: > >>> 1. actually log in (i.e. create a user, go to the login screen and log >>> in). You can wrap this in a single step definition like "Given I am >>> logged in as 'admin'", but you still have to go through the app within >>> the step definition. >> I do this. Here is example: >> >> Scenario: guest becomes a user >> Given I am guest >> When I go to the signup_path >> And puts signup info >> Then new user should be created >> And I should signin >> >>> Smth. >> >> Given /^I am guest$/ do >> get_me_the_cookies.should eq([]) >> end > > ^^ Givens, by definition, are given; to be taken for granted. They should not have expectations in them. If you feel the need to have an expectation in them, it suggests that there is another sceneario missing. > >> When /^I go to the signup_path$/ do >> visit signup_path >> end >> >> When /^puts signup info$/ do >> fill_in "user_username", :with => "frankpopp" >> fill_in "user_first", :with => "Frank" >> fill_in "user_second", :with => "Popp" >> fill_in "user_password", :with => "123456" >> fill_in "user_password_confirmation", :with => "123456" >> click_button "Sign up!" >> end >> >> Then /^new user should be created$/ do >> page.should have_content("New user added: frankpopp") >> end > > This doesn't tell you that the new user actually exists. Here I'd recommend going to the database: > > Then /^new user should be created$/ do > User.find_by_username("frankpopp").should_not be_nil > end > >> Then /^I should signin$/ do >> is_user?.should be_true >> end > > Your email earlier this thread has an "is_admin?" method, so I'll assume "is_user?" works the same way: > > def is_admin? ^^ That should have been is_user? > @current_user && @current_user.id != 1 > end > > The problem is that @current_user is an instance variable inside the controller. You can't access it from a scenario. Usually I just use something something on the page to identify that "frankpopp" is signed in. Also, if you want to specify that frankpopp is an admin, you can either check the database via the model (i.e. User.find_by_username("frankpopp").should be_admin or some such), or, again, look for some identifying feature on the page - maybe a link that only admins can see. >>> in users_controller.rb: >> def create >> @user = User.new(params[:user]) >> if @user.save >> session[:user_id] = @user.id # This create a session >> flash[:success] = "New user added: " + @user.username >> flash[:notice] = "His password is: " + @user.password if is_admin? >> redirect_to @user >> else >> >> end >> end > > HTH, > David BTW - while I do want to see you get the help you need, this conversation is noise for many rspec-users readers, so if you have all you need, please wait until you get your membership on the Cucumber list sorted out before continuing it. If things are still not working for you, however, please feel free to continue the conversation until this particular issue is resolved for you. Cheers, David From corbish at gmail.com Tue Nov 29 06:45:36 2011 From: corbish at gmail.com (Stuart Corbishley) Date: Tue, 29 Nov 2011 03:45:36 -0800 (PST) Subject: [rspec-users] Differences between rake spec & rspec spec Message-ID: <4b0e42ae-a87c-4b0b-b385-f202742ecedc@y7g2000vbe.googlegroups.com> Hi everyone, For the most part I've never had any issues running tests in a combination of rake spec and rspec spec. I ran into a weird issue today, when using CanCan and view tests. All the tests were passing under rspec spec, but rake spec failed them. I had a line like so: - if can? :activate, Learner - if learner.new_record? = f.input :active This was returning false, in the relevant test, it shouldn't have. So I dug deeper and put a raise in CanCan to inspect what was going on: def can?(*args) current_ability.can?(*args) raise "#{args}\n#{current_ability.inspect}" end This gave me two different results depending on rspec spec and rake spec. rspec spec: ActionView::Template::Error: [:index, School(id: integer, number: integer, name: string, unit_identity: string, sysid: string)] # To get around this I stubbed CanCan for the view tests, and the tests passed on both rake spec and rspec spec. So everything is good and well. But what strikes me is the absence of the @rules (coming from loading CanCan and the ability.rb file) in the rake spec task. Seems that rspec spec is doing the correct thing, but something isn't coming in when loaded on rake spec. I am aware there are differences (https://github.com/rspec/rspec-rails/ issues/208#issuecomment-413114) between the two, but not sure how that would affect this, or if just ignoring rake spec completely (what about the db stuff rake spec does)? Would enjoy hearing everyones thoughts.. From thibaut.barrere at gmail.com Tue Nov 29 11:02:05 2011 From: thibaut.barrere at gmail.com (=?UTF-8?Q?Thibaut_Barr=C3=A8re?=) Date: Tue, 29 Nov 2011 08:02:05 -0800 (PST) Subject: [rspec-users] Wrong number of arguments (reduce, rspec/core/metadata) In-Reply-To: <6659434.591.1322402797443.JavaMail.geo-discussion-forums@yqny18> References: <14899485.422.1320770706406.JavaMail.geo-discussion-forums@vbbdd1> <3E3F4489-76B4-414B-976D-6083282AF757@gmail.com> <6659434.591.1322402797443.JavaMail.geo-discussion-forums@yqny18> Message-ID: <13047340.1132.1322582525297.JavaMail.geo-discussion-forums@yqny18> In case it helps someone else: I couldn't find if the method was redefined by another class, but applying this patch solves the issue: https://github.com/rspec/rspec-core/commit/41c20dfc4e8bc99b6c7bba1e074883614d2aa656 (using inject instead of reduce). I'm on ruby 1.8.7 (2010-08-16 patchlevel 302). The issue happens with RSpec 2.7.0, but not with RSpec 2.5.0. -- Thibaut -------------- next part -------------- An HTML attachment was scrubbed... URL: From patrick at collinatorstudios.com Tue Nov 29 15:32:44 2011 From: patrick at collinatorstudios.com (Patrick J. Collins) Date: Tue, 29 Nov 2011 12:32:44 -0800 (PST) Subject: [rspec-users] is there a convention for testing that a record exists? Message-ID: In the app I am working on, there are a lot of observers for various models which call Event.create! to log stuff... So within a particular example, various records might be created in order to test behavior-- and this would result in several events being created. So say, I have a spec that does: it "creates an event when sharing a post" do user = create_user # this will make an event record of type "user created" post = create_post(:user => user) # this will make an event record of type "post created" post.share! # check to see that Event has a "post shared" event end ... Normally I would just do Event.last.event_type.should == "post shared" However, if the Event model has it's default_scope set to order records in a certain way, that test might fail. So I could do: Event.unscoped.last.event_type.should == "post shared" But then I begin thinking maybe it should be more like this: it "creates an event when sharing a post" do Event.exists?(:event_type => "post shared").should be_false user = create_user # this will make an event record of type "user created" post = create_post(:user => user) # this will make an event record of type "post created" post.share! Event.exists?(:event_type => "post shared").should be_true end ... I'm just not sure what's the best way to go, and if there's a convention for this sort of thing? Patrick J. Collins http://collinatorstudios.com From dchelimsky at gmail.com Tue Nov 29 22:19:48 2011 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 29 Nov 2011 21:19:48 -0600 Subject: [rspec-users] is there a convention for testing that a record exists? In-Reply-To: References: Message-ID: On Nov 29, 2011, at 2:32 PM, Patrick J. Collins wrote: > In the app I am working on, there are a lot of observers for various models > which call Event.create! to log stuff... So within a particular example, > various records might be created in order to test behavior-- and this would > result in several events being created. > > So say, I have a spec that does: > > it "creates an event when sharing a post" do > user = create_user # this will make an event record of type "user created" > post = create_post(:user => user) # this will make an event record of type "post created" > post.share! > > # check to see that Event has a "post shared" event > end > > ... > > Normally I would just do Event.last.event_type.should == "post shared" > > However, if the Event model has it's default_scope set to order records in a > certain way, that test might fail. > > So I could do: > > Event.unscoped.last.event_type.should == "post shared" > > But then I begin thinking maybe it should be more like this: > > it "creates an event when sharing a post" do > Event.exists?(:event_type => "post shared").should be_false > > user = create_user # this will make an event record of type "user created" > post = create_post(:user => user) # this will make an event record of type "post created" > post.share! > > Event.exists?(:event_type => "post shared").should be_true > end > > ... I'm just not sure what's the best way to go, and if there's a convention > for this sort of thing? I'm not aware of a solid convention for this. I tend to avoid the pairing of the 1st and last lines of the 2nd example. Are the events associated to the posts at all? If so you could specify post.events.map(&:event_type).should include("post shared") or some such.