From dark.red.and.yellow at googlemail.com Thu Jul 1 04:22:13 2010 From: dark.red.and.yellow at googlemail.com (=?ISO-8859-1?Q?Timo_R=F6=DFner?=) Date: Thu, 1 Jul 2010 01:22:13 -0700 (PDT) Subject: [rspec-users] rspec 2 not cleaning up after examples run? In-Reply-To: References: <6951BE91-9D73-4166-A0E4-7696E4AFF343@gmail.com> <522ebcc2-1d53-4e80-8302-67b224aa9bdb@k39g2000yqd.googlegroups.com> <2f27edf8-a9d4-4151-ad71-3e2500d99936@j4g2000yqh.googlegroups.com> Message-ID: @David, alright, I tried: bundle exec rspec spec/models/challenge_spec.rb -> Same results, same log output as above. @Amiruddin script/spec would be rails 2 / rspec 1 - my problem occurs with rails 3 / rspec 2 (and script/spec doesn't exist because of that). On Jun 30, 7:44?pm, Amiruddin Nagri wrote: > I am not sure if this will help or not but I was also getting data not > cleared properly when run specs through rake but when ran using script/spec > it was cleaning up the data > > Amir > > On Jun 30, 2010 10:56 PM, "David Chelimsky" wrote: > > On Jun 30, 2010, at 11:55 AM, Timo R??ner wrote: > > > On Jun 29, 12:14 pm, David Chelimsky > The command is rspec in rspec 2. Try: > > bundle exec rspec spec/models/challenge_spec.rb > > Cheers, > David > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.org > h... > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Thu Jul 1 08:15:45 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 07:15:45 -0500 Subject: [rspec-users] rspec 2 not cleaning up after examples run? In-Reply-To: References: <6951BE91-9D73-4166-A0E4-7696E4AFF343@gmail.com> <522ebcc2-1d53-4e80-8302-67b224aa9bdb@k39g2000yqd.googlegroups.com> <2f27edf8-a9d4-4151-ad71-3e2500d99936@j4g2000yqh.googlegroups.com> Message-ID: <5A93ED31-40AA-4991-B7A4-E95357179B86@gmail.com> On Jul 1, 2010, at 3:22 AM, Timo R??ner wrote: > On Jun 30, 7:44 pm, Amiruddin Nagri wrote: >> I am not sure if this will help or not but I was also getting data not >> cleared properly when run specs through rake but when ran using script/spec >> it was cleaning up the data >> >> Amir >> >> On Jun 30, 2010 10:56 PM, "David Chelimsky" wrote: >> >> On Jun 30, 2010, at 11:55 AM, Timo R??ner wrote: >> >>> On Jun 29, 12:14 pm, David Chelimsky > >> The command is rspec in rspec 2. Try: >> >> bundle exec rspec spec/models/challenge_spec.rb > @David, > > alright, I tried: > > bundle exec rspec spec/models/challenge_spec.rb > > -> Same results, same log output as above. > > @Amiruddin > > script/spec would be rails 2 / rspec 1 - my problem occurs with rails > 3 / rspec 2 (and script/spec doesn't exist because of that). Hard to break the top posting habit :) I moved your comments to the bottom. @Timo - I'm sorry I missed this the first time through, but it's because the spec_helper config is missing this line: config.use_transactional_fixtures = true The post-install hook when you install rspec-rails instructs you to re-run 'script/rails generate rspec:install', and if you do so you'll see this line in the generated spec_helper. Let me know if that solves it. I'm pretty sure it will. Cheers, David From florent2 at gmail.com Thu Jul 1 11:25:57 2010 From: florent2 at gmail.com (Florent Florent) Date: Thu, 1 Jul 2010 10:25:57 -0500 Subject: [rspec-users] using rSpec stub in Cucumber with rSpec2 Message-ID: Hello, I have a Rails3beta4 project where I want to use rSpec stubs in a Cucumber feature. Unfortunately it looks like requiring 'spec/stubs/cucumber' in env.rb does not work anymore: I get a "no such file to load -- spec/stubs/cucumber (LoadError)" error. Is it possible to use rSpec stubs in Cucumber with rSpec2? If not, is there any other viable alternative? Thanks for your help :) Florent -------------- next part -------------- An HTML attachment was scrubbed... URL: From ibrahim.awwal at gmail.com Thu Jul 1 12:13:48 2010 From: ibrahim.awwal at gmail.com (Ibrahim Awwal) Date: Thu, 1 Jul 2010 09:13:48 -0700 (PDT) Subject: [rspec-users] Rake spec options Message-ID: <0574e943-5f58-4e44-a87b-3a3f8cd7c305@u7g2000yqm.googlegroups.com> Hi guys, Apologies if this is a dumb question. I'm new to rails and most of the information online is about rails 2 and rspec 1.3, but my group is using rails 3 and thus rspec 2. I'm trying to format the output of rake spec, and I found online that I could use options like --format html in a file called spec/spec.opts in the rails base directory. However, from my attempts to populate this file and my cursory search through the rspec2 source, I don't think it obeys this file anymore. Furthermore, it seems like there is no more html format yet (makes sense, if rspec2 is a complete rewrite). So my question is, is there any way for me to a) specify options to be used when running rake spec and b) format the output nicely, specifically in html format but any alternative to the default is fine. The goal is basically to have the test results emailed out to the web development team each time someone pushes to git. I've got the rest of the script working, I just want to make it prettier. Thanks! -Ibrahim From dchelimsky at gmail.com Thu Jul 1 12:25:10 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 11:25:10 -0500 Subject: [rspec-users] Rake spec options In-Reply-To: <0574e943-5f58-4e44-a87b-3a3f8cd7c305@u7g2000yqm.googlegroups.com> References: <0574e943-5f58-4e44-a87b-3a3f8cd7c305@u7g2000yqm.googlegroups.com> Message-ID: On Jul 1, 2010, at 11:13 AM, Ibrahim Awwal wrote: > Hi guys, > Apologies if this is a dumb question. I'm new to rails and most of the > information online is about rails 2 and rspec 1.3, but my group is > using rails 3 and thus rspec 2. I'm trying to format the output of > rake spec, and I found online that I could use options like --format > html in a file called spec/spec.opts in the rails base directory. > However, from my attempts to populate this file and my cursory search > through the rspec2 source, I don't think it obeys this file anymore. > Furthermore, it seems like there is no more html format yet (makes > sense, if rspec2 is a complete rewrite). So my question is, is there > any way for me to a) specify options to be used when running rake spec > and b) format the output nicely, specifically in html format but any > alternative to the default is fine. > > The goal is basically to have the test results emailed out to the web > development team each time someone pushes to git. I've got the rest of > the script working, I just want to make it prettier. Thanks! HTML and TextMate formatters have yet to be added, but their on the list: http://github.com/rspec/rspec-core/issues. Cheers, David From ibrahim.awwal at gmail.com Thu Jul 1 12:27:21 2010 From: ibrahim.awwal at gmail.com (Ibrahim Awwal) Date: Thu, 1 Jul 2010 09:27:21 -0700 (PDT) Subject: [rspec-users] Rake spec options In-Reply-To: <0574e943-5f58-4e44-a87b-3a3f8cd7c305@u7g2000yqm.googlegroups.com> References: <0574e943-5f58-4e44-a87b-3a3f8cd7c305@u7g2000yqm.googlegroups.com> Message-ID: <46f0bd2c-99c2-4246-88c8-782f70624aa4@j4g2000yqh.googlegroups.com> On Jul 1, 9:13?am, Ibrahim Awwal wrote: > Hi guys, > Apologies if this is a dumb question. I'm new to rails and most of the > information online is about rails 2 and rspec 1.3, but my group is > using rails 3 and thus rspec 2. I'm trying to format the output of > rake spec, and I found online that I could use options like --format > html in a file called spec/spec.opts in the rails base directory. > However, from my attempts to populate this file and my cursory search > through the rspec2 source, I don't think it obeys this file anymore. > Furthermore, it seems like there is no more html format yet (makes > sense, if rspec2 is a complete rewrite). So my question is, is there > any way for me to a) specify options to be used when running rake spec > and b) format the output nicely, specifically in html format but any > alternative to the default is fine. > > The goal is basically to have the test results emailed out to the web > development team each time someone pushes to git. I've got the rest of > the script working, I just want to make it prettier. Thanks! > > -Ibrahim D'oh, I guess it was a dumb question. Searched this group and I found out that the proper file is now .rspec. Also found the answer on the formatters, looks like right now there's only documentation and progress formats? That's probably fine, I'll likely switch to documentation format because it's less verbose which is nicer for email. I'm still wondering one thing though, is it possible to disable colored output from a command line option? It seems like before you could pass --no-color but I'm not sure whether that's still the case now (I don't have access to my codebase right now so I can't test it myself). The reason being that right now when I redirect the output of rake spec into a file (rake spec > $tmp where tmp=`mktemp`) I get all the bash color escape sequences in the file, which is pretty useless for email. Thanks! -Ibrahim From ibrahim.awwal at gmail.com Thu Jul 1 12:41:21 2010 From: ibrahim.awwal at gmail.com (Ibrahim Awwal) Date: Thu, 1 Jul 2010 09:41:21 -0700 (PDT) Subject: [rspec-users] Rake spec options In-Reply-To: References: EC4CDC47-D16D-4CD2-8EED-3C9ABA270177@gmail.com Message-ID: On Jul 1, 9:25?am, David Chelimsky wrote: > On Jul 1, 2010, at 11:13 AM, Ibrahim Awwal wrote: > > > > > Hi guys, > > Apologies if this is a dumb question. I'm new to rails and most of the > > information online is about rails 2 and rspec 1.3, but my group is > > using rails 3 and thus rspec 2. I'm trying to format the output of > > rake spec, and I found online that I could use options like --format > > html in a file called spec/spec.opts in the rails base directory. > > However, from my attempts to populate this file and my cursory search > > through the rspec2 source, I don't think it obeys this file anymore. > > Furthermore, it seems like there is no more html format yet (makes > > sense, if rspec2 is a complete rewrite). So my question is, is there > > any way for me to a) specify options to be used when running rake spec > > and b) format the output nicely, specifically in html format but any > > alternative to the default is fine. > > > The goal is basically to have the test results emailed out to the web > > development team each time someone pushes to git. I've got the rest of > > the script working, I just want to make it prettier. Thanks! > > HTML and TextMate formatters have yet to be added, but their on the list: > > http://github.com/rspec/rspec-core/issues. > > Cheers, > David Thanks, that is helpful. Does the --no-color option work? I just installed rspec on my work computer and it seems to work but I just want to be sure, because it doesn't seem like it's there in the option parsing code, but I don't know how optparse works in ruby. Right now I have the output being fed into a perl script which strips the escape codes out but if I can get rid of that step it would be nice. -Ibrahim From dchelimsky at gmail.com Thu Jul 1 14:06:12 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 13:06:12 -0500 Subject: [rspec-users] Rake spec options In-Reply-To: References: EC4CDC47-D16D-4CD2-8EED-3C9ABA270177@gmail.com Message-ID: On Jul 1, 2010, at 11:41 AM, Ibrahim Awwal wrote: > On Jul 1, 9:25 am, David Chelimsky wrote: >> On Jul 1, 2010, at 11:13 AM, Ibrahim Awwal wrote: >> >> >> >>> Hi guys, >>> Apologies if this is a dumb question. I'm new to rails and most of the >>> information online is about rails 2 and rspec 1.3, but my group is >>> using rails 3 and thus rspec 2. I'm trying to format the output of >>> rake spec, and I found online that I could use options like --format >>> html in a file called spec/spec.opts in the rails base directory. >>> However, from my attempts to populate this file and my cursory search >>> through the rspec2 source, I don't think it obeys this file anymore. >>> Furthermore, it seems like there is no more html format yet (makes >>> sense, if rspec2 is a complete rewrite). So my question is, is there >>> any way for me to a) specify options to be used when running rake spec >>> and b) format the output nicely, specifically in html format but any >>> alternative to the default is fine. >> >>> The goal is basically to have the test results emailed out to the web >>> development team each time someone pushes to git. I've got the rest of >>> the script working, I just want to make it prettier. Thanks! >> >> HTML and TextMate formatters have yet to be added, but their on the list: >> >> http://github.com/rspec/rspec-core/issues. >> >> Cheers, >> David > > Thanks, that is helpful. Does the --no-color option work? I just > installed rspec on my work computer and it seems to work but I just > want to be sure, because it doesn't seem like it's there in the option > parsing code, but I don't know how optparse works in ruby. Right now I > have the output being fed into a perl script which strips the escape > codes out but if I can get rid of that step it would be nice. Check out what we do in rspec-core's own spec_helper: http://github.com/rspec/rspec-core/blob/master/spec/spec_helper.rb From akleak at gmail.com Thu Jul 1 14:27:03 2010 From: akleak at gmail.com (Arco) Date: Thu, 1 Jul 2010 11:27:03 -0700 (PDT) Subject: [rspec-users] using LINE with nested example groups Message-ID: I would like to use the --line parameter with nested example groups (describe / context). It looks to me like rspec handles this fine if I select the innermost group. But if I select an outer group, rspec ignores all the nested examples. Is this how it is meant to work?? Is there a way to make rspec run all the nested examples when I select an outer group?? thanks, Andy ps I'm using rspec 1.3.0, ruby 1.8.7, ubuntu 10.04. From dchelimsky at gmail.com Thu Jul 1 15:06:10 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 14:06:10 -0500 Subject: [rspec-users] using LINE with nested example groups In-Reply-To: References: Message-ID: On Jul 1, 2010, at 1:27 PM, Arco wrote: > I would like to use the --line parameter with nested example groups > (describe / context). > > It looks to me like rspec handles this fine if I select the innermost > group. > > But if I select an outer group, rspec ignores all the nested examples. > > Is this how it is meant to work?? > > Is there a way to make rspec run all the nested examples when I select > an outer group?? > > thanks, Andy > > ps I'm using rspec 1.3.0, ruby 1.8.7, ubuntu 10.04. This works as you expect in rspec-2, but does not in rspec-1. Cheers, David From ibrahim.awwal at gmail.com Thu Jul 1 02:52:49 2010 From: ibrahim.awwal at gmail.com (Ibrahim Awwal) Date: Wed, 30 Jun 2010 23:52:49 -0700 (PDT) Subject: [rspec-users] Rspec-rails 2 and spec/spec.opts or other configuration options for rake spec Message-ID: <60919101-8fe0-4131-87c1-ef23f800faaf@d8g2000yqf.googlegroups.com> Hi guys, I apologize if this is a dumb question, but in rspec-rails version 2.0.0.14 (for rails 3.0.0b4) I'm trying to add configuration options like some tutorials mention in a file spec/spec.opts, but this has no effect. I glanced through the source of rspec and I couldn't find anything where it reads this file anymore. Is there any way to add configuration options when running `rake spec`, or has this feature just not been added yet to the new version? Thanks, -Ibrahim From curtis.schofield at gmail.com Thu Jul 1 15:17:26 2010 From: curtis.schofield at gmail.com (Curtis) Date: Thu, 1 Jul 2010 12:17:26 -0700 Subject: [rspec-users] Entering text into a text field using rspec In-Reply-To: <1c3916b9-9d61-4a84-914e-d1b63927cf30@t10g2000yqg.googlegroups.com> References: <1c3916b9-9d61-4a84-914e-d1b63927cf30@t10g2000yqg.googlegroups.com> Message-ID: Check into capybara On Jun 29, 2010, at 4:44 PM, tester86 wrote: > HI > > I am new to rspec. I am at a web page and in that page I want to enter > in some text and then click send. > > it "will enter in some text 'asf'" do > > end > > what command would I used to enter in the text as I have searched > google but I cannot find any thing helpful. I do not want to use watir > as it relies on the ID and in our app the IDs change every time the > page is loaded. > > I tried :textfield => 'asf' > > But I get and error as it does not like the '. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From curtis.schofield at gmail.com Thu Jul 1 15:19:06 2010 From: curtis.schofield at gmail.com (Curtis) Date: Thu, 1 Jul 2010 12:19:06 -0700 Subject: [rspec-users] Entering text into a text field using rspec In-Reply-To: <1c3916b9-9d61-4a84-914e-d1b63927cf30@t10g2000yqg.googlegroups.com> References: <1c3916b9-9d61-4a84-914e-d1b63927cf30@t10g2000yqg.googlegroups.com> Message-ID: On Jun 29, 2010, at 4:44 PM, tester86 wrote: > HI > > I am new to rspec. I am at a web page and in that page I want to enter > in some text and then click send. > Sorry - toppost is a habit - check out capybara and see how it can be used stand alone with rspec to interact with the page > it "will enter in some text 'asf'" do > > end > > what command would I used to enter in the text as I have searched > google but I cannot find any thing helpful. I do not want to use watir > as it relies on the ID and in our app the IDs change every time the > page is loaded. > > I tried :textfield => 'asf' > > But I get and error as it does not like the '. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Thu Jul 1 15:21:29 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 14:21:29 -0500 Subject: [rspec-users] Rspec-rails 2 and spec/spec.opts or other configuration options for rake spec In-Reply-To: <60919101-8fe0-4131-87c1-ef23f800faaf@d8g2000yqf.googlegroups.com> References: <60919101-8fe0-4131-87c1-ef23f800faaf@d8g2000yqf.googlegroups.com> Message-ID: <835121F8-AD2C-4709-9756-0BE38C755521@gmail.com> On Jul 1, 2010, at 1:52 AM, Ibrahim Awwal wrote: > Hi guys, > I apologize if this is a dumb question, but in rspec-rails version > 2.0.0.14 (for rails 3.0.0b4) I'm trying to add configuration options > like some tutorials mention in a file spec/spec.opts, but this has no > effect. I glanced through the source of rspec and I couldn't find > anything where it reads this file anymore. Is there any way to add > configuration options when running `rake spec`, or has this feature > just not been added yet to the new version? Thanks, This has been addressed in an earlier email - I think this one was caught up in moderation. Please disregard. From dchelimsky at gmail.com Thu Jul 1 15:23:21 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 14:23:21 -0500 Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> Message-ID: On Jun 30, 2010, at 12:00 PM, ericindc wrote: > I am trying to use Shoulda matchers with the latest beta version of > RSpec for Rails 3. I've managed to track down the cause of my errors > to needing to explicitly set the subject, but the Shoulda examples > make no mention of requiring this step. I've pastied the errors I'm > receiving and adding subject { controller } seems to resolve them. Is > this behavior expected? > > http://pastie.org/1020788 Have you tried pinging the shoulda maintainers? From dchelimsky at gmail.com Thu Jul 1 15:27:52 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 14:27:52 -0500 Subject: [rspec-users] Cookie assignment and reading In-Reply-To: References: Message-ID: <541656C0-803E-4177-BD22-0F2946353A0E@gmail.com> On Jun 29, 2010, at 4:05 PM, Josh Clayton wrote: > Hello all, > > I'm running the latest stable rspec/rspec-rails (1.3.0/1.3.2) in a > Rails 2.3.8 app and am having trouble testing that a cookie gets > deleted. > > In a semi-convoluted manner, I am essentially running code from the > rdoc as such: > > describe MyController, "GET index" do > let(:cookie_value) { "of course" } > > it "should delete the cookie" do > cookies[:awesome] = cookie_value > get :index > cookies[:awesome].should == cookie_value > end > end > > This is obviously example code but the outcome effect is the same - > trying to find the value of a cookie I set with RSpec fails. For my > specific, real-life example, I'm assigning a cooking and performing a > request in the before block and testing that the cookie is deleted. > It's passing, but incorrectly (since I haven't performed the deletion > in my controller action). > > Any insight would be appreciated; thanks! That should work. Please file a bug: http://rspec.lighthouseapp.com/ Thx, David From dchelimsky at gmail.com Thu Jul 1 15:28:59 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 14:28:59 -0500 Subject: [rspec-users] How to test index method of a controller ? In-Reply-To: <0b66dfe3-6a59-421d-8e00-ec911d0a9251@k39g2000yqb.googlegroups.com> References: <0b66dfe3-6a59-421d-8e00-ec911d0a9251@k39g2000yqb.googlegroups.com> Message-ID: <25927A64-21F7-4574-BA9D-A25E41B3FFDF@gmail.com> On Jun 29, 2010, at 5:08 PM, marcioa1 wrote: > Hi, > > My index methods > > def index > @galleries = Gallery.filtered_by(params.reverse_merge!(:per_page => > 10)) > end > > > My spec: > > it "should list all galleries" do > get :index > response.should render_template("index") > end > > And the error message > > should list all galleries > can't convert Spec::Mocks::Mock into Array > > The problem is with the filtered_by method. What should I pass ? Please post the full spec. There is some code assigning a mock somewhere, but it's not in the code you provided. Thanks, David From ibrahim.awwal at gmail.com Thu Jul 1 19:03:17 2010 From: ibrahim.awwal at gmail.com (Ibrahim Awwal) Date: Thu, 1 Jul 2010 16:03:17 -0700 (PDT) Subject: [rspec-users] Rake spec options In-Reply-To: References: EC4CDC47-D16D-4CD2-8EED-3C9ABA270177@gmail.com Message-ID: <32e59640-2efd-4862-bdf6-39398e745c1e@b4g2000pra.googlegroups.com> On Jul 1, 11:06?am, David Chelimsky wrote: > On Jul 1, 2010, at 11:41 AM, Ibrahim Awwal wrote: > > > > > On Jul 1, 9:25 am, David Chelimsky wrote: > >> On Jul 1, 2010, at 11:13 AM, Ibrahim Awwal wrote: > > >>> Hi guys, > >>> Apologies if this is a dumb question. I'm new to rails and most of the > >>> information online is about rails 2 and rspec 1.3, but my group is > >>> using rails 3 and thus rspec 2. I'm trying to format the output of > >>> rake spec, and I found online that I could use options like --format > >>> html in a file called spec/spec.opts in the rails base directory. > >>> However, from my attempts to populate this file and my cursory search > >>> through the rspec2 source, I don't think it obeys this file anymore. > >>> Furthermore, it seems like there is no more html format yet (makes > >>> sense, if rspec2 is a complete rewrite). So my question is, is there > >>> any way for me to a) specify options to be used when running rake spec > >>> and b) format the output nicely, specifically in html format but any > >>> alternative to the default is fine. > > >>> The goal is basically to have the test results emailed out to the web > >>> development team each time someone pushes to git. I've got the rest of > >>> the script working, I just want to make it prettier. Thanks! > > >> HTML and TextMate formatters have yet to be added, but their on the list: > > >>http://github.com/rspec/rspec-core/issues. > > >> Cheers, > >> David > > > Thanks, that is helpful. Does the --no-color option work? I just > > installed rspec on my work computer and it seems to work but I just > > want to be sure, because it doesn't seem like it's there in the option > > parsing code, but I don't know how optparse works in ruby. Right now I > > have the output being fed into a perl script which strips the escape > > codes out but if I can get rid of that step it would be nice. > > Check out what we do in rspec-core's own spec_helper: > > http://github.com/rspec/rspec-core/blob/master/spec/spec_helper.rb Ah I see, thanks very much! I've been very surprised and amazed by the help you've given me. Apologies for the double post, the first one went into the moderation queue because I didn't see the thing about registering on mailman as well but after I did that I posted again because I assumed that the other one just wouldn't get approved. -Ibrahim From ericmilford at gmail.com Thu Jul 1 21:40:01 2010 From: ericmilford at gmail.com (ericindc) Date: Thu, 1 Jul 2010 18:40:01 -0700 (PDT) Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> Message-ID: <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> I have a thread open on their group page as well, but the only response received thus far seems to think it's an RSpec issue. I am having the same issue in my model tests as well. On Jul 1, 3:23?pm, David Chelimsky wrote: > On Jun 30, 2010, at 12:00 PM, ericindc wrote: > > > I am trying to use Shoulda matchers with the latest beta version of > > RSpec for Rails 3. ?I've managed to track down the cause of my errors > > to needing to explicitly set the subject, but the Shoulda examples > > make no mention of requiring this step. ?I've pastied the errors I'm > > receiving and adding subject { controller } seems to resolve them. ?Is > > this behavior expected? > > >http://pastie.org/1020788 > > Have you tried pinging the shoulda maintainers? > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Thu Jul 1 21:47:09 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 20:47:09 -0500 Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> Message-ID: On Jul 1, 2010, at 8:40 PM, ericindc wrote: > On Jul 1, 3:23 pm, David Chelimsky wrote: >> On Jun 30, 2010, at 12:00 PM, ericindc wrote: >> >>> I am trying to use Shoulda matchers with the latest beta version of >>> RSpec for Rails 3. I've managed to track down the cause of my errors >>> to needing to explicitly set the subject, but the Shoulda examples >>> make no mention of requiring this step. I've pastied the errors I'm >>> receiving and adding subject { controller } seems to resolve them. Is >>> this behavior expected? >> >>> http://pastie.org/1020788 >> >> Have you tried pinging the shoulda maintainers? > > I have a thread open on their group page as well, but the only > response received thus far seems to think it's an RSpec issue. Link? > I am having the same issue in my model tests as well. ps - please bottom and/or inline post. Read http://idallen.com/topposting.html for more info. From ericmilford at gmail.com Thu Jul 1 22:01:16 2010 From: ericmilford at gmail.com (ericindc) Date: Thu, 1 Jul 2010 19:01:16 -0700 (PDT) Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> Message-ID: http://groups.google.com/group/shoulda/browse_thread/thread/9a19ca5f60285e2d On Jul 1, 9:47?pm, David Chelimsky wrote: > On Jul 1, 2010, at 8:40 PM, ericindc wrote: > > > > > > > On Jul 1, 3:23 pm, David Chelimsky wrote: > >> On Jun 30, 2010, at 12:00 PM, ericindc wrote: > > >>> I am trying to use Shoulda matchers with the latest beta version of > >>> RSpec for Rails 3. ?I've managed to track down the cause of my errors > >>> to needing to explicitly set the subject, but the Shoulda examples > >>> make no mention of requiring this step. ?I've pastied the errors I'm > >>> receiving and adding subject { controller } seems to resolve them. ?Is > >>> this behavior expected? > > >>>http://pastie.org/1020788 > > >> Have you tried pinging the shoulda maintainers? > > > I have a thread open on their group page as well, but the only > > response received thus far seems to think it's an RSpec issue. > > Link? > > > I am having the same issue in my model tests as well. > > ps - please bottom and/or inline post. Readhttp://idallen.com/topposting.htmlfor more info. > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Thu Jul 1 22:32:04 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 21:32:04 -0500 Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> Message-ID: <34C8308B-8C53-446A-8471-C7581436407B@gmail.com> On Jul 1, 2010, at 9:01 PM, ericindc wrote: > On Jul 1, 9:47 pm, David Chelimsky wrote: >> On Jul 1, 2010, at 8:40 PM, ericindc wrote: >>> On Jul 1, 3:23 pm, David Chelimsky wrote: >>>> On Jun 30, 2010, at 12:00 PM, ericindc wrote: >> >>>>> I am trying to use Shoulda matchers with the latest beta version of >>>>> RSpec for Rails 3. I've managed to track down the cause of my errors >>>>> to needing to explicitly set the subject, but the Shoulda examples >>>>> make no mention of requiring this step. I've pastied the errors I'm >>>>> receiving and adding subject { controller } seems to resolve them. Is >>>>> this behavior expected? >> >>>>> http://pastie.org/1020788 >> >>>> Have you tried pinging the shoulda maintainers? >> >>> I have a thread open on their group page as well, but the only >>> response received thus far seems to think it's an RSpec issue. >> >> Link? >> >>> I am having the same issue in my model tests as well. >> >> ps - please bottom and/or inline post. Readhttp://idallen.com/topposting.htmlfor more info. > http://groups.google.com/group/shoulda/browse_thread/thread/9a19ca5f60285e2d Can you show me the version of your code (with the subject workaround) that works? From ericmilford at gmail.com Thu Jul 1 22:35:43 2010 From: ericmilford at gmail.com (ericindc) Date: Thu, 1 Jul 2010 19:35:43 -0700 (PDT) Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: <34C8308B-8C53-446A-8471-C7581436407B@gmail.com> References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> <34C8308B-8C53-446A-8471-C7581436407B@gmail.com> Message-ID: <41a6818f-f26b-4577-9733-5a45b394bbaf@u26g2000yqu.googlegroups.com> Here is the full controller spec that is passing...removing the subject line fails all bu the render_template. require 'spec_helper' describe HomepageController do describe "routes" do it { should route(:get, "/").to(:action => :index) } end describe "on GET to :index" do before(:each) do get :index end subject { controller } it { should respond_with(:success) } it { should render_template(:index) } it { should_not set_the_flash } end end On Jul 1, 10:32?pm, David Chelimsky wrote: > On Jul 1, 2010, at 9:01 PM, ericindc wrote: > > > > > > > On Jul 1, 9:47 pm, David Chelimsky wrote: > >> On Jul 1, 2010, at 8:40 PM, ericindc wrote: > >>> On Jul 1, 3:23 pm, David Chelimsky wrote: > >>>> On Jun 30, 2010, at 12:00 PM, ericindc wrote: > > >>>>> I am trying to use Shoulda matchers with the latest beta version of > >>>>> RSpec for Rails 3. ?I've managed to track down the cause of my errors > >>>>> to needing to explicitly set the subject, but the Shoulda examples > >>>>> make no mention of requiring this step. ?I've pastied the errors I'm > >>>>> receiving and adding subject { controller } seems to resolve them. ?Is > >>>>> this behavior expected? > > >>>>>http://pastie.org/1020788 > > >>>> Have you tried pinging the shoulda maintainers? > > >>> I have a thread open on their group page as well, but the only > >>> response received thus far seems to think it's an RSpec issue. > > >> Link? > > >>> I am having the same issue in my model tests as well. > > >> ps - please bottom and/or inline post. Readhttp://idallen.com/topposting.htmlformore info. > >http://groups.google.com/group/shoulda/browse_thread/thread/9a19ca5f6... > > Can you show me the version of your code (with the subject workaround) that works? > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Thu Jul 1 23:10:12 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 22:10:12 -0500 Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: <41a6818f-f26b-4577-9733-5a45b394bbaf@u26g2000yqu.googlegroups.com> References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> <34C8308B-8C53-446A-8471-C7581436407B@gmail.com> <41a6818f-f26b-4577-9733-5a45b394bbaf@u26g2000yqu.googlegroups.com> Message-ID: <5ED2E2DF-6786-4CC8-99B9-04999E215A99@gmail.com> On Jul 1, 2010, at 9:35 PM, ericindc wrote: > > > On Jul 1, 10:32 pm, David Chelimsky wrote: >> On Jul 1, 2010, at 9:01 PM, ericindc wrote: >> >> >> >> >> >>> On Jul 1, 9:47 pm, David Chelimsky wrote: >>>> On Jul 1, 2010, at 8:40 PM, ericindc wrote: >>>>> On Jul 1, 3:23 pm, David Chelimsky wrote: >>>>>> On Jun 30, 2010, at 12:00 PM, ericindc wrote: >> >>>>>>> I am trying to use Shoulda matchers with the latest beta version of >>>>>>> RSpec for Rails 3. I've managed to track down the cause of my errors >>>>>>> to needing to explicitly set the subject, but the Shoulda examples >>>>>>> make no mention of requiring this step. I've pastied the errors I'm >>>>>>> receiving and adding subject { controller } seems to resolve them. Is >>>>>>> this behavior expected? >> >>>>>>> http://pastie.org/1020788 >> >>>>>> Have you tried pinging the shoulda maintainers? >> >>>>> I have a thread open on their group page as well, but the only >>>>> response received thus far seems to think it's an RSpec issue. >> >>>> Link? >> >>>>> I am having the same issue in my model tests as well. >> >>>> ps - please bottom and/or inline post. Readhttp://idallen.com/topposting.htmlformore info. >>> http://groups.google.com/group/shoulda/browse_thread/thread/9a19ca5f6... >> >> Can you show me the version of your code (with the subject workaround) that works? > Here is the full controller spec that is passing...removing the > subject line fails all bu the render_template. > > require 'spec_helper' > > describe HomepageController do > > describe "routes" do > it { should route(:get, "/").to(:action => :index) } > end > > > describe "on GET to :index" do > before(:each) do > get :index > end > > subject { controller } > > it { should respond_with(:success) } > it { should render_template(:index) } > it { should_not set_the_flash } > end > > end It's a shoulda issue, which I've raised (including a patch) in the shoulda tracker: http://github.com/thoughtbot/shoulda/issues/issue/112 Please feel free to follow and comment on that issue. Cheers, David From ericmilford at gmail.com Thu Jul 1 23:32:23 2010 From: ericmilford at gmail.com (ericindc) Date: Thu, 1 Jul 2010 20:32:23 -0700 (PDT) Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: <5ED2E2DF-6786-4CC8-99B9-04999E215A99@gmail.com> References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> <34C8308B-8C53-446A-8471-C7581436407B@gmail.com> <41a6818f-f26b-4577-9733-5a45b394bbaf@u26g2000yqu.googlegroups.com> <5ED2E2DF-6786-4CC8-99B9-04999E215A99@gmail.com> Message-ID: <44ffcbc3-bd29-45d3-bd3f-237cf6a7ff42@u7g2000yqm.googlegroups.com> Will do, thanks! On Jul 1, 11:10?pm, David Chelimsky wrote: > On Jul 1, 2010, at 9:35 PM, ericindc wrote: > > > > > > > > > On Jul 1, 10:32 pm, David Chelimsky wrote: > >> On Jul 1, 2010, at 9:01 PM, ericindc wrote: > > >>> On Jul 1, 9:47 pm, David Chelimsky wrote: > >>>> On Jul 1, 2010, at 8:40 PM, ericindc wrote: > >>>>> On Jul 1, 3:23 pm, David Chelimsky wrote: > >>>>>> On Jun 30, 2010, at 12:00 PM, ericindc wrote: > > >>>>>>> I am trying to use Shoulda matchers with the latest beta version of > >>>>>>> RSpec for Rails 3. ?I've managed to track down the cause of my errors > >>>>>>> to needing to explicitly set the subject, but the Shoulda examples > >>>>>>> make no mention of requiring this step. ?I've pastied the errors I'm > >>>>>>> receiving and adding subject { controller } seems to resolve them. ?Is > >>>>>>> this behavior expected? > > >>>>>>>http://pastie.org/1020788 > > >>>>>> Have you tried pinging the shoulda maintainers? > > >>>>> I have a thread open on their group page as well, but the only > >>>>> response received thus far seems to think it's an RSpec issue. > > >>>> Link? > > >>>>> I am having the same issue in my model tests as well. > > >>>> ps - please bottom and/or inline post. Readhttp://idallen.com/topposting.htmlformoreinfo. > >>>http://groups.google.com/group/shoulda/browse_thread/thread/9a19ca5f6... > > >> Can you show me the version of your code (with the subject workaround) that works? > > Here is the full controller spec that is passing...removing the > > subject line fails all bu the render_template. > > > require 'spec_helper' > > > describe HomepageController do > > > ?describe "routes" do > > ? ?it { should route(:get, "/").to(:action => :index) } > > ?end > > > ?describe "on GET to :index" do > > ? ?before(:each) do > > ? ? ?get :index > > ? ?end > > > ? ?subject { controller } > > > ? ?it { should respond_with(:success) } > > ? ?it { should render_template(:index) } > > ? ?it { should_not set_the_flash } > > ?end > > > end > > It's a shoulda issue, which I've raised (including a patch) in the shoulda tracker:http://github.com/thoughtbot/shoulda/issues/issue/112 > > Please feel free to follow and comment on that issue. > > Cheers, > David > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Thu Jul 1 23:43:54 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 1 Jul 2010 22:43:54 -0500 Subject: [rspec-users] Shoulda and explicit subject In-Reply-To: <44ffcbc3-bd29-45d3-bd3f-237cf6a7ff42@u7g2000yqm.googlegroups.com> References: <13f56045-f2d1-4c88-8186-b481739cef81@b35g2000yqi.googlegroups.com> <8c68a923-6125-4e9c-a1fe-8100d6c41880@e5g2000yqn.googlegroups.com> <34C8308B-8C53-446A-8471-C7581436407B@gmail.com> <41a6818f-f26b-4577-9733-5a45b394bbaf@u26g2000yqu.googlegroups.com> <5ED2E2DF-6786-4CC8-99B9-04999E215A99@gmail.com> <44ffcbc3-bd29-45d3-bd3f-237cf6a7ff42@u7g2000yqm.googlegroups.com> Message-ID: On Jul 1, 2010, at 10:32 PM, ericindc wrote: > On Jul 1, 11:10 pm, David Chelimsky wrote: >> On Jul 1, 2010, at 9:35 PM, ericindc wrote: >>> On Jul 1, 10:32 pm, David Chelimsky wrote: >>>> On Jul 1, 2010, at 9:01 PM, ericindc wrote: >>>>> On Jul 1, 9:47 pm, David Chelimsky wrote: >>>>>> On Jul 1, 2010, at 8:40 PM, ericindc wrote: >>>>>>> On Jul 1, 3:23 pm, David Chelimsky wrote: >>>>>>>> On Jun 30, 2010, at 12:00 PM, ericindc wrote: >> >>>>>>>>> I am trying to use Shoulda matchers with the latest beta version of >>>>>>>>> RSpec for Rails 3. I've managed to track down the cause of my errors >>>>>>>>> to needing to explicitly set the subject, but the Shoulda examples >>>>>>>>> make no mention of requiring this step. I've pastied the errors I'm >>>>>>>>> receiving and adding subject { controller } seems to resolve them. Is >>>>>>>>> this behavior expected? >> >>>>>>>>> http://pastie.org/1020788 >> >>>>>>>> Have you tried pinging the shoulda maintainers? >> >>>>>>> I have a thread open on their group page as well, but the only >>>>>>> response received thus far seems to think it's an RSpec issue. >> >>>>>> Link? >> >>>>>>> I am having the same issue in my model tests as well. >> >>>>>> ps - please bottom and/or inline post. Readhttp://idallen.com/topposting.htmlformoreinfo. >>>>> http://groups.google.com/group/shoulda/browse_thread/thread/9a19ca5f6... >> >>>> Can you show me the version of your code (with the subject workaround) that works? >>> Here is the full controller spec that is passing...removing the >>> subject line fails all bu the render_template. >> >>> require 'spec_helper' >> >>> describe HomepageController do >> >>> describe "routes" do >>> it { should route(:get, "/").to(:action => :index) } >>> end >> >>> describe "on GET to :index" do >>> before(:each) do >>> get :index >>> end >> >>> subject { controller } >> >>> it { should respond_with(:success) } >>> it { should render_template(:index) } >>> it { should_not set_the_flash } >>> end >> >>> end >> >> It's a shoulda issue, which I've raised (including a patch) in the shoulda tracker:http://github.com/thoughtbot/shoulda/issues/issue/112 >> >> Please feel free to follow and comment on that issue. > Will do, thanks! And please, please, please stop top-posting! http://idallen.com/topposting.html Cheers, David From florent2 at gmail.com Fri Jul 2 00:59:47 2010 From: florent2 at gmail.com (Florent Florent) Date: Thu, 1 Jul 2010 23:59:47 -0500 Subject: [rspec-users] using rSpec stub in Cucumber with rSpec2 Message-ID: > > Hello, > > I have a Rails3beta4 project where I want to use rSpec stubs in a Cucumber > feature. Unfortunately it looks like requiring 'spec/stubs/cucumber' in > env.rb does not work anymore: I get a "no such file to load -- > spec/stubs/cucumber (LoadError)" error. > > Is it possible to use rSpec stubs in Cucumber with rSpec2? If not, is > there > any other viable alternative? > Alask has updated Cucumber so that we can now use RSpec 2 mockings frameworks: http://wiki.github.com/aslakhellesoy/cucumber/mocking-and-stubbing-with-cucumber -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at ruby-forum.com Fri Jul 2 01:48:03 2010 From: lists at ruby-forum.com (Woody Peterson) Date: Fri, 2 Jul 2010 07:48:03 +0200 Subject: [rspec-users] RSpec 2.0, Cucumber, ruby-debug In-Reply-To: <7FD627D7-9930-4D1A-B723-8370D8A39802@gmail.com> References: <655ab45b-00b4-415e-9ba9-d3080124295d@k39g2000yqd.googlegroups.com> <99ab4094-6a48-43cb-968f-c8ea7a2e13b6@u26g2000yqu.googlegroups.com> <7FD627D7-9930-4D1A-B723-8370D8A39802@gmail.com> Message-ID: > What are you experiencing and what are you expecting? If you use rspec in cucumber, cucumber doesn't support --debug as an option, so you can't use debuggers in cucumber + rspec. Given RSpec 2.0's api, the expected behavior is declaring --debug + debugger drops you into a debugger, and the experience is an unsupported option error from cucumber. However, in my opinion, the expected behavior after declaring a debugger is to be dropped into a debug session without an extra option. Once you've played with it a little, then I could imagine wanting to turn 'em off for a sec before removing them entirely. So I'd rather have --no-debug myself. -- Posted via http://www.ruby-forum.com/. From akleak at gmail.com Fri Jul 2 12:11:19 2010 From: akleak at gmail.com (Arco) Date: Fri, 2 Jul 2010 09:11:19 -0700 (PDT) Subject: [rspec-users] Rspec2 / Rails3 / test_unit Message-ID: <40e950e0-6025-406f-ada6-64e8e0d49c95@s24g2000pri.googlegroups.com> I generate a new rails3 app using "rails new my_app -T". Then i run "cd my_app ; rails generate", and I don't see any test_unit options. (as expected). Then I put "gem 'rspec-rails'" into my Gemfile, and re-run "rails generate". Now I see options for test_unit. TestUnit: test_unit:controller test_unit:helper test_unit:integration ... Why does it show options for test_unit? Is this expected? Tx, Andy Rails Beta4, Rspec Beta15, Ruby 1.8.7, Ubuntu 10.04 From joshua.clayton at gmail.com Fri Jul 2 12:21:20 2010 From: joshua.clayton at gmail.com (Josh Clayton) Date: Fri, 2 Jul 2010 09:21:20 -0700 (PDT) Subject: [rspec-users] Cookie assignment and reading In-Reply-To: <541656C0-803E-4177-BD22-0F2946353A0E@gmail.com> References: <541656C0-803E-4177-BD22-0F2946353A0E@gmail.com> Message-ID: David, Thanks; I thought I was going crazy! The ticket is here: https://rspec.lighthouseapp.com/projects/5645-rspec/tickets/1023-cookie-assignment-and-reading-doesnt-work-if-both-occur-in-the-same-spec Thanks again! On Jul 1, 3:27?pm, David Chelimsky wrote: > On Jun 29, 2010, at 4:05 PM, Josh Clayton wrote: > > > > > > > Hello all, > > > I'm running the latest stable rspec/rspec-rails (1.3.0/1.3.2) in a > > Rails 2.3.8 app and am having trouble testing that a cookie gets > > deleted. > > > In a semi-convoluted manner, I am essentially running code from the > > rdoc as such: > > > ? ?describe MyController, "GET index" do > > ? ? ?let(:cookie_value) { "of course" } > > > ? ? ?it "should delete the cookie" do > > ? ? ? ?cookies[:awesome] = cookie_value > > ? ? ? ?get :index > > ? ? ? ?cookies[:awesome].should == cookie_value > > ? ? ?end > > ? ?end > > > This is obviously example code but the outcome effect is the same - > > trying to find the value of a cookie I set with RSpec fails. ?For my > > specific, real-life example, I'm assigning a cooking and performing a > > request in the before block and testing that the cookie is deleted. > > It's passing, but incorrectly (since I haven't performed the deletion > > in my controller action). > > > Any insight would be appreciated; thanks! > > That should work. Please file a bug:http://rspec.lighthouseapp.com/ > > Thx, > David > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From curtis.schofield at gmail.com Fri Jul 2 12:22:57 2010 From: curtis.schofield at gmail.com (Curtis) Date: Fri, 2 Jul 2010 09:22:57 -0700 Subject: [rspec-users] RSpec 2.0, Cucumber, ruby-debug In-Reply-To: References: <655ab45b-00b4-415e-9ba9-d3080124295d@k39g2000yqd.googlegroups.com> <99ab4094-6a48-43cb-968f-c8ea7a2e13b6@u26g2000yqu.googlegroups.com> <7FD627D7-9930-4D1A-B723-8370D8A39802@gmail.com> Message-ID: On Jul 1, 2010, at 10:48 PM, Woody Peterson wrote: >> What are you experiencing and what are you expecting? > > If you use rspec in cucumber, cucumber doesn't support --debug as an > option, so you can't use debuggers in cucumber + rspec. > > Given RSpec 2.0's api, the expected behavior is declaring --debug + > debugger drops you into a debugger, and the experience is an > unsupported > option error from cucumber. > > However, in my opinion, the expected behavior after declaring a > debugger > is to be dropped into a debug session without an extra option. Once > you've played with it a little, then I could imagine wanting to turn > 'em > off for a sec before removing them entirely. So I'd rather have > --no-debug myself. > -- I imagine the --debug flag is to avoid any errant debugger calls from flaking out production. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Fri Jul 2 14:19:28 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 2 Jul 2010 13:19:28 -0500 Subject: [rspec-users] Rspec2 / Rails3 / test_unit In-Reply-To: <40e950e0-6025-406f-ada6-64e8e0d49c95@s24g2000pri.googlegroups.com> References: <40e950e0-6025-406f-ada6-64e8e0d49c95@s24g2000pri.googlegroups.com> Message-ID: <4B2141B1-A742-4198-86CB-42B1E431E688@gmail.com> On Jul 2, 2010, at 11:11 AM, Arco wrote: > I generate a new rails3 app using "rails new my_app -T". > > Then i run "cd my_app ; rails generate", and I don't see any test_unit > options. (as expected). > > Then I put "gem 'rspec-rails'" into my Gemfile, and re-run "rails > generate". > > Now I see options for test_unit. > TestUnit: > test_unit:controller > test_unit:helper > test_unit:integration > ... > > Why does it show options for test_unit? Is this expected? This is not anything that RSpec is doing in any intentional way. rspec-rails does require 'test/unit/assertions' and 'test/unit/assertionfailederror', but not 'test/unit' (top level). I'd guess it's something to do with rspec-rails generators telling rails to use them for testing, so it also shows you the other testing possibilities. But that's just a guess. > > Tx, Andy > > Rails Beta4, Rspec Beta15, Ruby 1.8.7, Ubuntu 10.04 From patgannon at gmail.com Fri Jul 2 20:25:15 2010 From: patgannon at gmail.com (Patrick Gannon) Date: Fri, 2 Jul 2010 17:25:15 -0700 Subject: [rspec-users] [Rails] Stubbed static methods are bleeding over into other specs and making them fail Message-ID: Hi all, I'm having a problem where stubbed static methods aren't properly becoming "unstubbed". I have tried manually unstubbing them, but it still doesn't work. Spec is as follows: it "creates user accounts for unknown users" do Notification.stub(:deliver_routed) User.should_receive(:create).with({:email => "sally at etestflight.com"}) User.should_receive(:create).with({:email => "joe at etestflight.com"}) User.stub!(:find_by_email).with("sally at etestflight.com") { nil } User.stub!(:find_by_email).with("joe at etestflight.com") { nil } User.stub!(:find_by_email).with("bill at etestflight.com") { User.new } begin post :route, :id => "37", :email_addresses => "sally at etestflight.com, joe at etestflight.com, bill at etestflight.com" ensure User.unstub! :find_by_email #User.unstub! :method_missing User.rspec_reset end end It will pass, but then another spec fails with: "undefined method `find_by_email' for Object:Class". The other spec passes when I create a database User and rely on the real definition of User.find_by_email *(defined by method_missing in MongoMapper's Document module)* in this spec instead of stubbing out the calls to find_by_email. As you can see, I tried calling "unstub!" on find_by_email, and calling rspec_reset, and it doesn't make any difference (other spec still fails). I even tried un-stubbing method_missing (since that's what defines the real find_by_email) and it complains that that was never stubbed. I am running Rails 3 beta 4 with RSpec and rspec-rails beta 13 (tried pointing Gemfile to the GIT repository and did a 'bundle install', but it still installed beta 13 instead of 15 for some reason). Here is a list of the gems I have installed (via bundle show) Gems included by the bundle: * abstract (1.0.0) * actionmailer (3.0.0.beta4) * actionpack (3.0.0.beta4) * activemodel (3.0.0.beta4) * activerecord (3.0.0.beta4) * activeresource (3.0.0.beta4) * activesupport (3.0.0.beta4) * arel (0.4.0) * bcrypt-ruby (2.1.2) * bson (1.0.3) * bson_ext (1.0.1) * builder (2.1.2) * bundler (1.0.0.beta.2) * capistrano (2.5.19) * capybara (0.3.8 35e81a4) * cucumber (0.8.3) * cucumber-rails (0.3.2 b75110d) * culerity (0.2.10) * database_cleaner (0.5.2 7ea99d7) * devise (1.1.rc1 88ab2fe) * diff-lcs (1.1.2) * erubis (2.6.6) * factory_girl (1.3.0) * factory_girl_rails (1.0) * faker (0.3.1) * ffi (0.6.3) * gherkin (2.0.2) * highline (1.5.2) * i18n (0.4.1) * jnunemaker-validatable (1.8.4) * joint (0.3.2 11a094d) * json_pure (1.4.3) * mail (2.2.5) * mime-types (1.16) * mongo (1.0.3) * mongo_mapper (0.8.2) * net-scp (1.0.2) * net-sftp (2.0.4) * net-ssh (2.0.23) * net-ssh-gateway (1.0.1) * nokogiri (1.4.2.1) * plucky (0.3.2) * polyglot (0.3.1) * rack (1.2.1) * rack-test (0.5.4) * rails (3.0.0.beta4 f8720a0) * railties (3.0.0.beta4) * rake (0.8.7) * rspec (2.0.0.beta.13) * rspec-core (2.0.0.beta.13) * rspec-expectations (2.0.0.beta.13) * rspec-mocks (2.0.0.beta.13) * rspec-rails (2.0.0.beta.13) * selenium-webdriver (0.0.24) * term-ansicolor (1.0.5) * thor (0.13.7) * treetop (1.4.8) * trollop (1.16.2) * tzinfo (0.3.22) * wand (0.2.1) * warden (0.10.7) * webrat (0.7.1) Thank you! Pat -------------- next part -------------- An HTML attachment was scrubbed... URL: From jolohaga at me.com Fri Jul 2 19:46:46 2010 From: jolohaga at me.com (Jose Hales-Garcia) Date: Fri, 02 Jul 2010 16:46:46 -0700 Subject: [rspec-users] Beginning writing RSpec with Rails model plugin Message-ID: <21D45980-D9EA-411B-A944-B07FF51A8270@me.com> I want to write a Rails model plugin using RSpec. I'm using Rails 3, Ruby 1.9 and RSpec 2. I've read the RSpec and Rails documentation but haven't found any examples of using RSpec in a Rails 3 plugin situation. Is there a plugin someone can recommend that I can study that would help me set up the environment and set me on the task of writing code? Sincerely, Jose From dgoldie15 at gmail.com Sat Jul 3 02:20:27 2010 From: dgoldie15 at gmail.com (Doug) Date: Fri, 2 Jul 2010 23:20:27 -0700 (PDT) Subject: [rspec-users] rspec controller test strange error: undefined method `call' for nil:NilClass Message-ID: <978d6dbe-f7e9-41f8-828e-1e95196a2e50@b4g2000pra.googlegroups.com> must be doing something dumb.... not sure, but the 'call' appears to be on the block.call when the respond_to block gets executed. straight forward "channels" resource with a 'create' action.... only new thing is just assigning the current_user to the model. def create @channel = Channel.new(params[:channel]) @channel.user = @user respond_to do |format| if @channel.save flash[:notice] = 'Channel was successfully created.' redirect_to(@channel) else flash[:error] = 'Error saving Channel.' render :action => "new" end end end -------- modifying the scaffold spec like this produces strange def mock_channel(stubs={}) @mock_channel ||= mock_model(Channel, stubs) end def mock_user(stubs={}) @mock_user ||= mock_model(User, stubs) end before(:each) do @mock_user = mock_user controller.stub(:current_user).and_return @mock_user end describe "POST create" do describe "with valid params" do it "assigns a newly created channel as @channel" do mock_channel(:save => true) @mock_channel.should_receive(:user=).with(@mock_user) Channel.stub(:new).with({'these' => 'params'}).and_return(mock_channel) debugger post :create, :channel => {:these => 'params'} assigns[:channel].should equal(mock_channel) end ------ it fails on the post :create line ....reporting undefined method `call' for nil:NilClass at .../.rvm/gems/ruby-1.8.7-p249/gems/activesupport-2.3.5/lib/ active_support/whiny_nil.rb:52 raise_nil_warning_for klass, method, caller 51 else 52 super 53 end 54 end another clue perhaps is that if you remove the :save => true stub option, then it works ...but fails at the if @channel.save line .....reporting Mock "Channel_1002" received unexpected message :save with (no args) thanks in advance From trev at trevreport.org Sat Jul 3 02:40:20 2010 From: trev at trevreport.org (Lalish-Menagh, Trevor) Date: Sat, 3 Jul 2010 02:40:20 -0400 Subject: [rspec-users] Help with nested routes test in Rails 3 Message-ID: Hi all, I must be doing something wrong here. Could someone point me in the right direction? I am trying to test my nested resources in Rails 3. The route: resources :students do resources :days end The test: it "recognizes and generates #index" do { :get => "/students/1/days" }.should route_to(:controller => "days", :action => "index", :student_id => "1") end The error: 1) DaysController routing nested in students recognizes and generates #index Failure/Error: { :get => "/students/1/days" }.should route_to(:student_id => "1", :controller => "days", :action => "index") found extras <{:student_id=>"1"}>, not <{}> The route works find in the browser, I just don't know what I am missing to make the test pass. Yours, Trevor -- Trevor Lalish-Menagh 484.868.6150 mobile trev at trevreport.org http://www.trevmex.com/ From michael at schuerig.de Sat Jul 3 16:34:42 2010 From: michael at schuerig.de (Michael Schuerig) Date: Sat, 3 Jul 2010 22:34:42 +0200 Subject: [rspec-users] Loading problem with engine extending ActionController::Base Message-ID: <201007032234.42820.michael@schuerig.de> I'm working on an engine that extends ActionController::Base like this module MyEngine class Engine < Rails::Engine config.after_initialize do ActionController::Base.class_eval do include MyEngine::ControllerExtension end end end end This works in the development environment (rails server). It does not work for specs. No matter if I run rake spec or rspec spec/some_spec.rb. rake spec indirectly loads the application through this line in Rakefile require File.expand_path('../config/application', __FILE__) in the normal course of rake initialization. During this, ActionController::Base is loaded and the #after_initialize callback of MyEngine is called. Then, when a spec is loaded, that in turn loads spec/spec_helper.rb, containing this line require File.dirname(__FILE__) + "/../config/environment" unless defined?(Rails) Which causes, among other things, a reload of ActionController::Base, but this time the engine callback is *not* executed. Thus, the specs blow up as soon as they run into a method defined in the engine. But, wait, why is that require executed at all? Isn't Rails defined at that point? Apparently it is not and I have no idea why. rspec spec/some_spec.rb is slightly different. Here ActionController::Base is loaded just once, but the engine callback is not executed. rspec and associated gems are 2.0.0.beta.15 rails is 3.0.0.beta4 I'm stumped. Michael -- Michael Schuerig mailto:michael at schuerig.de http://www.schuerig.de/michael/ From dchelimsky at gmail.com Sat Jul 3 16:43:42 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 3 Jul 2010 15:43:42 -0500 Subject: [rspec-users] Loading problem with engine extending ActionController::Base In-Reply-To: <201007032234.42820.michael@schuerig.de> References: <201007032234.42820.michael@schuerig.de> Message-ID: <203A8E17-F779-4F50-A2E2-BA2FC3B4E6BB@gmail.com> On Jul 3, 2010, at 3:34 PM, Michael Schuerig wrote: > I'm working on an engine that extends ActionController::Base like this > > module MyEngine > class Engine < Rails::Engine > > config.after_initialize do > ActionController::Base.class_eval do > include MyEngine::ControllerExtension > end > end > end > end > > This works in the development environment (rails server). It does not > work for specs. No matter if I run rake spec or rspec spec/some_spec.rb. > > > rake spec indirectly loads the application through this line in Rakefile > > require File.expand_path('../config/application', __FILE__) > > in the normal course of rake initialization. During this, > ActionController::Base is loaded and the #after_initialize callback of > MyEngine is called. > > Then, when a spec is loaded, that in turn loads spec/spec_helper.rb, > containing this line > > require File.dirname(__FILE__) + "/../config/environment" unless > defined?(Rails) This is from an old version of the spec_helper. Be sure to follow the post-install instructions (that's what they're there for) and run "script/rails generate rspec:install". The newer generated spec_helper uses File.expand_path for this require, so it doesn't load the file a second time. I believe that will fix this issue for you. HTH, David > > Which causes, among other things, a reload of ActionController::Base, > but this time the engine callback is *not* executed. Thus, the specs > blow up as soon as they run into a method defined in the engine. But, > wait, why is that require executed at all? Isn't Rails defined at that > point? Apparently it is not and I have no idea why. > > rspec spec/some_spec.rb is slightly different. Here > ActionController::Base is loaded just once, but the engine callback is > not executed. > > rspec and associated gems are 2.0.0.beta.15 > rails is 3.0.0.beta4 > > I'm stumped. > > Michael From michael at schuerig.de Sat Jul 3 17:40:00 2010 From: michael at schuerig.de (Michael Schuerig) Date: Sat, 3 Jul 2010 23:40:00 +0200 Subject: [rspec-users] Loading problem with engine extending ActionController::Base In-Reply-To: <203A8E17-F779-4F50-A2E2-BA2FC3B4E6BB@gmail.com> References: <201007032234.42820.michael@schuerig.de> <203A8E17-F779-4F50-A2E2-BA2FC3B4E6BB@gmail.com> Message-ID: <201007032340.00828.michael@schuerig.de> On Saturday 03 July 2010, David Chelimsky wrote: > On Jul 3, 2010, at 3:34 PM, Michael Schuerig wrote: [double loading of Rails framework classes] > > require File.dirname(__FILE__) + "/../config/environment" unless > > defined?(Rails) > > This is from an old version of the spec_helper. Be sure to follow the > post-install instructions (that's what they're there for) and run > "script/rails generate rspec:install". Indeed, you're right. I compared old and new visually (only) and didn't notice the difference. As I have some stuff in spec_helper.rb, I don't like to overwrite it. > The newer generated spec_helper uses File.expand_path for this > require, so it doesn't load the file a second time. I believe that > will fix this issue for you. Unfortunately and surprisingly not. I'm using ruby 1.8.7 (2010-06-23 patchlevel 299) [x86_64-linux] in case that makes a difference. I can work around this by including the required extension explicitly in ApplicationController, of course. Michael -- Michael Schuerig mailto:michael at schuerig.de http://www.schuerig.de/michael/ From ashley.moran at patchspace.co.uk Sun Jul 4 15:00:47 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sun, 4 Jul 2010 20:00:47 +0100 Subject: [rspec-users] [ANN] database_resetter 0.1.0 Message-ID: <4387D4C1-067B-40AE-89B6-BDB82312C0DE@patchspace.co.uk> Hi all Apologies for cross-posting and spam in the same post. Hopefully you'll let me off this once... I just released my first gem (woo!), database_resetter[1]. It's designed to completely rebuild your Rails/Merb etc database before a Cucumber/RSpec every time a migration changes. Basically it prevents you seeing "unknown column" etc errors because you forgot to migrate the DB before a test run. It's complementary to, not a replacement for, database_cleaner. database_resetter runs 0-1 times per Cucumber/RSpec run, whereas database_cleaner runs 0-1 times per Cucumber scenario / RSpec example. I've been using it for a year or two, but only just got round to packaging it up. It doesn't do much, but over hundreds of database rebuilds the time savings add up to a fair bit. I've used it "untested"* until now, but I spent today putting some Cucumber features around it. They aren't perfect, but they sanity check most of what it does. There's a ReadMe in the gem with full instructions (they're as good as I could manage after a long day). The official source is in a darcs repo hosted on Patch-Tag[2]. Feedback gratefully received - let me know if you find it useful, and please contact me with bug reports / feature requests. Like I say, this is my first gem, so I'm not expecting it to work well in the wild... Cheers Ash [1] http://rubygems.org/gems/database_resetter [2] https://patch-tag.com/r/ashleymoran/database_resetter/home * it works on my machine -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From trev at trevreport.org Sun Jul 4 16:28:39 2010 From: trev at trevreport.org (Lalish-Menagh, Trevor) Date: Sun, 4 Jul 2010 16:28:39 -0400 Subject: [rspec-users] Help with nested routes test in Rails 3 In-Reply-To: References: Message-ID: Hi again, I figured out the issue. RSpec's route_to wraps Rails' assert_routing, which checks two things: - Rails recognizes the given path and routes it to a particular spot in your application (via assert_recognizes) - a particular set of options generate a particular path (via assert_generates) The problem (in my example below) is that the set of options given: {:controller => "days", :action => "index", :student_id => "1"} generates the path: "/days" not: "/student/1/days" Rails doesn't take into account the foreign key of nested resources when generating a path from a set of options. Now that I understand this, I can write a test just using assert_recognizes that passes: assert_recognizes({:controller => "days", :action => "index", :student_id => "1"}, "/students/1/days") Hooray! I hope this helps someone else out there. It was really confusing me. Yours, Trevor On Sat, Jul 3, 2010 at 2:40 AM, Lalish-Menagh, Trevor wrote: > Hi all, > > I must be doing something wrong here. Could someone point me in the > right direction? I am trying to test my nested resources in Rails 3. > > The route: > ?resources :students do > ? ?resources :days > ?end > > The test: > ? ? ?it "recognizes and generates #index" do > ? ? ? ?{ :get => "/students/1/days" }.should route_to(:controller => > "days", :action => "index", :student_id => "1") > ? ? ?end > > The error: > 1) DaysController routing nested in students recognizes and generates #index > ? ?Failure/Error: { :get => "/students/1/days" }.should > route_to(:student_id => "1", :controller => "days", :action => > "index") > ? ?found extras <{:student_id=>"1"}>, not <{}> > > The route works find in the browser, I just don't know what I am > missing to make the test pass. > > Yours, > Trevor > -- > Trevor Lalish-Menagh > 484.868.6150 mobile > trev at trevreport.org > http://www.trevmex.com/ > -- Trevor Lalish-Menagh 484.868.6150 mobile trev at trevreport.org http://www.trevmex.com/ From lists at ruby-forum.com Sun Jul 4 20:15:03 2010 From: lists at ruby-forum.com (Frank Mattia) Date: Mon, 5 Jul 2010 02:15:03 +0200 Subject: [rspec-users] spec'ing namespaced routes Message-ID: <9d5c5172fb9e56dea0c65606915456b2@ruby-forum.com> What's the appropriate way to test namespaced routes with rspec-2 & rails 3? I imagined that the following would work but it does not. describe Admin::UsersController do describe "routing" do it "recognizes and generates #index" do { :get => "/admin/users" }.should route_to(:controller => "admin_users", :action => "index") end end end In fact, { :get => "/admin/users" }.should be_routable fails as well. Yet rake routes disagrees. Any suggestions? -- Posted via http://www.ruby-forum.com/. From win at wincent.com Mon Jul 5 03:00:52 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 5 Jul 2010 09:00:52 +0200 Subject: [rspec-users] Possible improvements to routing spec API Message-ID: Hi folks, I've been unhappy with routing specs for a long time now and last night when updating some old 1.3 specs for 2.0 I decided to see if I could come up with something that didn't make me feel unhappy. Principal causes of unhappiness: 1. Historically we had "route_for" and "params_from", which felt awfully repetitive because we ended up doing: route_for(lengthy_hash_of_params).should == string_or_hash_describing_destination params_from(list_describing_destination).should == lengthy_hash_of_params Of course, it was worse than that in practice because those two lines usually appeared in separate example blocks with the associated boilerplate. It felt like a lot of work for testing such a simple thing. It also felt irritating to have to repeat basically the same thing twice but in a different order. 2. So then RSpec gave us "route_to", which is a wrapper for Rails' "assert_routing"; being a bi-directional test that encompasses the function of both "assert_recognizes" and "assert_generates", this allows us to avoid some, or even all, of the repetition: { :get => 'foo' }.should route_to(:controller => 'foo', :action => 'index') The unhappiness here comes from three causes: One is that { :get => 'foo' } feels inconsistent with other places in RSpec like controller specs where "get" is a method, so we can do things like "get 'thing'". The second issue is that the "to" in "route_to" feels misleadingly uni-directional when in reality it is a bi-directional test. The third issue is that for routes which don't actually have that bi-directional mapping, "route_to" can't be used and we must instead drop down to Rails' assert_recognizes() and/or assert_generates() methods, or wrap them using our own matchers. So I thought about what I would rather be writing and in my first cut came up with this: describe ArticlesController do describe 'routing' do example 'GET /wiki' do get('/wiki').should map_to(:controller => 'articles', :action => 'index') get('/wiki').should map_from(:controller => 'articles', :action => 'index') articles_path.should == '/wiki' end end end Things to note: - make the bi-directionality of the mapping explicit by having separate "map_to" and "map_from" lines. - for ease of readability and writability, keep the order as "method -> path -> destination" for both assertions by using "to" and "from", rather than swapping the order around - "map" here is the right verb because we've always used that language to talk about how a given URL "maps to" a given controller#action. And remember how in the router DSL prior to Rails 3 everything in config/routes.rb started with "map"? - I've tacked a test for the "articles_path" URL helper in there, because as a user of the Rails router I generally want to know two things: firstly, that requests get mapped to the appropriate controller#action; and secondly, that when I generate URLs (almost exclusively with named helpers; I use "url_for" in only 4 places in my entire app) that they take me where I think they take me. In the end, however, I moved this into a separate "describe 'URL helpers'" block. - conscious use of "example" rather than "it" because I want my specs to be identified as "ArticlesController routing GET /wiki" and not "ArticlesController routing recognizes and generates #index". - the repetition is a conscious choice because I value readability/scannability over DRYness-at-all-costs, especially in specs; the following is more DRY, for example, but less readable/scannable: path = '/wiki' destination = { :controller => 'articles, :action => 'index' } get(path).should map_to(destination) get(path).should map_from(destination) So I went ahead and converted a bunch of specs to this syntax and found that, surprise, surprise, in an application like this one where almost everything consists of a "standard" RESTful resource, over 90% of routes were testable in the bi-directional sense and in a typical routing spec file I needed to use "map_to" with no corresponding "map_from" for only one or two cases. So I needed a new method that meant "map_to_and_from". Funnily, I just can't decide on a name for this method. As a placeholder I am just using "map" for now: get('/wiki').should map(:controller => 'articles', :action => 'index') But others I have tried are: get('/wiki').should map_as(:controller => 'articles', :action => 'index') get('/wiki').should map_via(:controller => 'articles', :action => 'index') get('/wiki').should map_with(:controller => 'articles', :action => 'index') get('/wiki').should map_to_and_from(:controller => 'articles', :action => 'index') get('/wiki').should map_both(:controller => 'articles', :action => 'index') get('/wiki').should map_both_ways(:controller => 'articles', :action => 'index') get('/wiki').should have_routing(:controller => 'articles', :action => 'index') get('/wiki').should have_route(:controller => 'articles', :action => 'index') get('/wiki').should be_route(:controller => 'articles', :action => 'index') get('/wiki').should be_routing(:controller => 'articles', :action => 'index') get('/wiki').should route_as(:controller => 'articles', :action => 'index') get('/wiki').should route_via(:controller => 'articles', :action => 'index') get('/wiki').should route(:controller => 'articles', :action => 'index') get('/wiki').should <=> (:controller => 'articles', :action => 'index') get('/wiki').should > (:controller => 'articles', :action => 'index') # map_to get('/wiki').should < (:controller => 'articles', :action => 'index') # map_from If anybody has a suitable suggestion please let me know. In the meantime, here is an example of a spec file that has been converted to use this new "API": http://gist.github.com/464081 It also includes the supporting code that adds these new "map", "map_to", "map_from" matchers, and the "get", "post", "put" and "delete" methods. All of this for Rails 3/RSpec 2 only. I'm going to convert more routing specs and see if any more changes are needed to handle edge cases, but for a first cut I am pretty happy with the results, apart from my inability to decide on the right name for the bi-directional "map" matcher. Cheers, Wincent From matt at mattwynne.net Mon Jul 5 05:14:17 2010 From: matt at mattwynne.net (Matt Wynne) Date: Mon, 5 Jul 2010 10:14:17 +0100 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: Message-ID: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> On 5 Jul 2010, at 08:00, Wincent Colaiuta wrote: > Hi folks, > > I've been unhappy with routing specs for a long time now and last night when updating some old 1.3 specs for 2.0 I decided to see if I could come up with something that didn't make me feel unhappy. > > Principal causes of unhappiness: > > 1. Historically we had "route_for" and "params_from", which felt awfully repetitive because we ended up doing: > > route_for(lengthy_hash_of_params).should == string_or_hash_describing_destination > params_from(list_describing_destination).should == lengthy_hash_of_params > > Of course, it was worse than that in practice because those two lines usually appeared in separate example blocks with the associated boilerplate. It felt like a lot of work for testing such a simple thing. It also felt irritating to have to repeat basically the same thing twice but in a different order. > > 2. So then RSpec gave us "route_to", which is a wrapper for Rails' "assert_routing"; being a bi-directional test that encompasses the function of both "assert_recognizes" and "assert_generates", this allows us to avoid some, or even all, of the repetition: > > { :get => 'foo' }.should route_to(:controller => 'foo', :action => 'index') > > The unhappiness here comes from three causes: > > One is that { :get => 'foo' } feels inconsistent with other places in RSpec like controller specs where "get" is a method, so we can do things like "get 'thing'". > > The second issue is that the "to" in "route_to" feels misleadingly uni-directional when in reality it is a bi-directional test. > > The third issue is that for routes which don't actually have that bi-directional mapping, "route_to" can't be used and we must instead drop down to Rails' assert_recognizes() and/or assert_generates() methods, or wrap them using our own matchers. > > So I thought about what I would rather be writing and in my first cut came up with this: > > describe ArticlesController do > describe 'routing' do > example 'GET /wiki' do > get('/wiki').should map_to(:controller => 'articles', :action => 'index') > get('/wiki').should map_from(:controller => 'articles', :action => 'index') > articles_path.should == '/wiki' > end > end > end > > Things to note: > > - make the bi-directionality of the mapping explicit by having separate "map_to" and "map_from" lines. > > - for ease of readability and writability, keep the order as "method -> path -> destination" for both assertions by using "to" and "from", rather than swapping the order around > > - "map" here is the right verb because we've always used that language to talk about how a given URL "maps to" a given controller#action. And remember how in the router DSL prior to Rails 3 everything in config/routes.rb started with "map"? > > - I've tacked a test for the "articles_path" URL helper in there, because as a user of the Rails router I generally want to know two things: firstly, that requests get mapped to the appropriate controller#action; and secondly, that when I generate URLs (almost exclusively with named helpers; I use "url_for" in only 4 places in my entire app) that they take me where I think they take me. In the end, however, I moved this into a separate "describe 'URL helpers'" block. > > - conscious use of "example" rather than "it" because I want my specs to be identified as "ArticlesController routing GET /wiki" and not "ArticlesController routing recognizes and generates #index". > > - the repetition is a conscious choice because I value readability/scannability over DRYness-at-all-costs, especially in specs; the following is more DRY, for example, but less readable/scannable: > > path = '/wiki' > destination = { :controller => 'articles, :action => 'index' } > get(path).should map_to(destination) > get(path).should map_from(destination) > > So I went ahead and converted a bunch of specs to this syntax and found that, surprise, surprise, in an application like this one where almost everything consists of a "standard" RESTful resource, over 90% of routes were testable in the bi-directional sense and in a typical routing spec file I needed to use "map_to" with no corresponding "map_from" for only one or two cases. So I needed a new method that meant "map_to_and_from". > > Funnily, I just can't decide on a name for this method. As a placeholder I am just using "map" for now: > > get('/wiki').should map(:controller => 'articles', :action => 'index') > > But others I have tried are: > > get('/wiki').should map_as(:controller => 'articles', :action => 'index') > get('/wiki').should map_via(:controller => 'articles', :action => 'index') > get('/wiki').should map_with(:controller => 'articles', :action => 'index') > get('/wiki').should map_to_and_from(:controller => 'articles', :action => 'index') > get('/wiki').should map_both(:controller => 'articles', :action => 'index') > get('/wiki').should map_both_ways(:controller => 'articles', :action => 'index') > get('/wiki').should have_routing(:controller => 'articles', :action => 'index') > get('/wiki').should have_route(:controller => 'articles', :action => 'index') > get('/wiki').should be_route(:controller => 'articles', :action => 'index') > get('/wiki').should be_routing(:controller => 'articles', :action => 'index') > get('/wiki').should route_as(:controller => 'articles', :action => 'index') > get('/wiki').should route_via(:controller => 'articles', :action => 'index') > get('/wiki').should route(:controller => 'articles', :action => 'index') > get('/wiki').should <=> (:controller => 'articles', :action => 'index') > get('/wiki').should > (:controller => 'articles', :action => 'index') # map_to > get('/wiki').should < (:controller => 'articles', :action => 'index') # map_from > > If anybody has a suitable suggestion please let me know. > > In the meantime, here is an example of a spec file that has been converted to use this new "API": > > http://gist.github.com/464081 > > It also includes the supporting code that adds these new "map", "map_to", "map_from" matchers, and the "get", "post", "put" and "delete" methods. All of this for Rails 3/RSpec 2 only. > > I'm going to convert more routing specs and see if any more changes are needed to handle edge cases, but for a first cut I am pretty happy with the results, apart from my inability to decide on the right name for the bi-directional "map" matcher. > > Cheers, > Wincent Seems like progress. One thought: Why not use a macro-style syntax to eliminate the boring boilerplate call to #it / #example and generate examples instead? > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Mon Jul 5 07:56:22 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 06:56:22 -0500 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> Message-ID: <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> On Jul 5, 2010, at 4:14 AM, Matt Wynne wrote: > On 5 Jul 2010, at 08:00, Wincent Colaiuta wrote: >> Hi folks, >> >> I've been unhappy with routing specs for a long time now and last night when updating some old 1.3 specs for 2.0 I decided to see if I could come up with something that didn't make me feel unhappy. >> >> Principal causes of unhappiness: >> >> 1. Historically we had "route_for" and "params_from", which felt awfully repetitive because we ended up doing: >> >> route_for(lengthy_hash_of_params).should == string_or_hash_describing_destination >> params_from(list_describing_destination).should == lengthy_hash_of_params >> >> Of course, it was worse than that in practice because those two lines usually appeared in separate example blocks with the associated boilerplate. It felt like a lot of work for testing such a simple thing. It also felt irritating to have to repeat basically the same thing twice but in a different order. >> >> 2. So then RSpec gave us "route_to", which is a wrapper for Rails' "assert_routing"; being a bi-directional test that encompasses the function of both "assert_recognizes" and "assert_generates", this allows us to avoid some, or even all, of the repetition: >> >> { :get => 'foo' }.should route_to(:controller => 'foo', :action => 'index') >> >> The unhappiness here comes from three causes: >> >> One is that { :get => 'foo' } feels inconsistent with other places in RSpec like controller specs where "get" is a method, so we can do things like "get 'thing'". >> >> The second issue is that the "to" in "route_to" feels misleadingly uni-directional when in reality it is a bi-directional test. >> >> The third issue is that for routes which don't actually have that bi-directional mapping, "route_to" can't be used and we must instead drop down to Rails' assert_recognizes() and/or assert_generates() methods, or wrap them using our own matchers. This is the source of confusion/trouble that others have brought up here on this list as well. Thanks for identifying the underlying issue. >> So I thought about what I would rather be writing and in my first cut came up with this: >> >> describe ArticlesController do >> describe 'routing' do >> example 'GET /wiki' do >> get('/wiki').should map_to(:controller => 'articles', :action => 'index') >> get('/wiki').should map_from(:controller => 'articles', :action => 'index') >> articles_path.should == '/wiki' >> end >> end >> end >> >> Things to note: >> >> - make the bi-directionality of the mapping explicit by having separate "map_to" and "map_from" lines. >> >> - for ease of readability and writability, keep the order as "method -> path -> destination" for both assertions by using "to" and "from", rather than swapping the order around >> >> - "map" here is the right verb because we've always used that language to talk about how a given URL "maps to" a given controller#action. And remember how in the router DSL prior to Rails 3 everything in config/routes.rb started with "map"? >> >> - I've tacked a test for the "articles_path" URL helper in there, because as a user of the Rails router I generally want to know two things: firstly, that requests get mapped to the appropriate controller#action; and secondly, that when I generate URLs (almost exclusively with named helpers; I use "url_for" in only 4 places in my entire app) that they take me where I think they take me. In the end, however, I moved this into a separate "describe 'URL helpers'" block. >> >> - conscious use of "example" rather than "it" because I want my specs to be identified as "ArticlesController routing GET /wiki" and not "ArticlesController routing recognizes and generates #index". >> >> - the repetition is a conscious choice because I value readability/scannability over DRYness-at-all-costs, especially in specs; the following is more DRY, for example, but less readable/scannable: >> >> path = '/wiki' >> destination = { :controller => 'articles, :action => 'index' } >> get(path).should map_to(destination) >> get(path).should map_from(destination) >> >> So I went ahead and converted a bunch of specs to this syntax and found that, surprise, surprise, in an application like this one where almost everything consists of a "standard" RESTful resource, over 90% of routes were testable in the bi-directional sense and in a typical routing spec file I needed to use "map_to" with no corresponding "map_from" for only one or two cases. So I needed a new method that meant "map_to_and_from". >> >> Funnily, I just can't decide on a name for this method. As a placeholder I am just using "map" for now: >> >> get('/wiki').should map(:controller => 'articles', :action => 'index') >> >> But others I have tried are: >> >> get('/wiki').should map_as(:controller => 'articles', :action => 'index') >> get('/wiki').should map_via(:controller => 'articles', :action => 'index') >> get('/wiki').should map_with(:controller => 'articles', :action => 'index') >> get('/wiki').should map_to_and_from(:controller => 'articles', :action => 'index') >> get('/wiki').should map_both(:controller => 'articles', :action => 'index') >> get('/wiki').should map_both_ways(:controller => 'articles', :action => 'index') >> get('/wiki').should have_routing(:controller => 'articles', :action => 'index') >> get('/wiki').should have_route(:controller => 'articles', :action => 'index') >> get('/wiki').should be_route(:controller => 'articles', :action => 'index') >> get('/wiki').should be_routing(:controller => 'articles', :action => 'index') >> get('/wiki').should route_as(:controller => 'articles', :action => 'index') >> get('/wiki').should route_via(:controller => 'articles', :action => 'index') >> get('/wiki').should route(:controller => 'articles', :action => 'index') >> get('/wiki').should <=> (:controller => 'articles', :action => 'index') >> get('/wiki').should > (:controller => 'articles', :action => 'index') # map_to >> get('/wiki').should < (:controller => 'articles', :action => 'index') # map_from >> >> If anybody has a suitable suggestion please let me know. Naming is hard. >> In the meantime, here is an example of a spec file that has been converted to use this new "API": >> >> http://gist.github.com/464081 Nice overall. Much of the code belongs in Rails, though, so I'd like to try to get a patch in to Rails once we get this worked out. I'd like the rspec-rails matchers to be simple wrappers for rails' assertions wherever possible. >> It also includes the supporting code that adds these new "map", "map_to", "map_from" matchers, and the "get", "post", "put" and "delete" methods. All of this for Rails 3/RSpec 2 only. >> >> I'm going to convert more routing specs and see if any more changes are needed to handle edge cases, but for a first cut I am pretty happy with the results, apart from my inability to decide on the right name for the bi-directional "map" matcher. I think having three separate matchers would land us in a good spot. The wrapped rails assertions also accept a hash representing query params, so let's see if we can accommodate that as well: get('/something', :ref_id => '1234').should route_to(....) >> >> Cheers, >> Wincent > > Seems like progress. One thought: Why not use a macro-style syntax to eliminate the boring boilerplate call to #it / #example and generate examples instead? Something like: describe "The router" do it { should recognize(get('/wiki/foo').as("wiki#show", :id => 'foo') } it { should generate(get('/wiki/foo').from("wiki#show", :id => 'foo') } it { should route(get('/wiki/foo').to("wiki#show", :id => 'foo') } end That's definitely nice and clean, and it makes it easier to align the names with the rails assertions, which I think adds some value. The output could be formatted something like this: The router should recognize get('/wiki/foo') as wiki#show with :id => 'foo' should generate get('/wiki/foo') from wiki#show with :id => 'foo' should route get('/wiki/foo') to wiki#show with :id => 'foo' Thoughts? From dchelimsky at gmail.com Mon Jul 5 08:02:50 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 07:02:50 -0500 Subject: [rspec-users] spec'ing namespaced routes In-Reply-To: <9d5c5172fb9e56dea0c65606915456b2@ruby-forum.com> References: <9d5c5172fb9e56dea0c65606915456b2@ruby-forum.com> Message-ID: On Jul 4, 2010, at 7:15 PM, Frank Mattia wrote: > What's the appropriate way to test namespaced routes with rspec-2 & > rails 3? > > I imagined that the following would work but it does not. > > describe Admin::UsersController do > describe "routing" do > it "recognizes and generates #index" do > { :get => "/admin/users" }.should route_to(:controller => > "admin_users", :action => "index") > end > end > end > > In fact, > > { :get => "/admin/users" }.should be_routable > > fails as well. Yet rake routes disagrees. > > Any suggestions? This is a deficiency in the API recognized and discussed in http://groups.google.com/group/rspec/browse_thread/thread/50b46ca3e4bd3a78 (which came after your post). Please feel free to follow and/or contribute to that conversation. Cheers, David From dchelimsky at gmail.com Mon Jul 5 08:04:42 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 07:04:42 -0500 Subject: [rspec-users] Help with nested routes test in Rails 3 In-Reply-To: References: Message-ID: On Jul 4, 2010, at 3:28 PM, Lalish-Menagh, Trevor wrote: > > On Sat, Jul 3, 2010 at 2:40 AM, Lalish-Menagh, Trevor > wrote: >> Hi all, >> >> I must be doing something wrong here. Could someone point me in the >> right direction? I am trying to test my nested resources in Rails 3. >> >> The route: >> resources :students do >> resources :days >> end >> >> The test: >> it "recognizes and generates #index" do >> { :get => "/students/1/days" }.should route_to(:controller => >> "days", :action => "index", :student_id => "1") >> end >> >> The error: >> 1) DaysController routing nested in students recognizes and generates #index >> Failure/Error: { :get => "/students/1/days" }.should >> route_to(:student_id => "1", :controller => "days", :action => >> "index") >> found extras <{:student_id=>"1"}>, not <{}> >> >> The route works find in the browser, I just don't know what I am >> missing to make the test pass. >> >> Yours, >> Trevor > Hi again, > > I figured out the issue. RSpec's route_to wraps Rails' assert_routing, > which checks two things: > - Rails recognizes the given path and routes it to a particular spot > in your application (via assert_recognizes) > - a particular set of options generate a particular path (via assert_generates) > > The problem (in my example below) is that the set of options given: > {:controller => "days", :action => "index", :student_id => "1"} > generates the path: > "/days" > not: > "/student/1/days" > > Rails doesn't take into account the foreign key of nested resources > when generating a path from a set of options. > > Now that I understand this, I can write a test just using > assert_recognizes that passes: > assert_recognizes({:controller => "days", :action => "index", > :student_id => "1"}, "/students/1/days") > > Hooray! > > I hope this helps someone else out there. It was really confusing me. > > Yours, > Trevor Please join the conversation about improving the API for routing specs: http://groups.google.com/group/rspec/browse_thread/thread/50b46ca3e4bd3a78 Cheers, David From win at wincent.com Mon Jul 5 10:04:03 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 5 Jul 2010 16:04:03 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> Message-ID: El 05/07/2010, a las 13:56, David Chelimsky escribi?: > Nice overall. Much of the code belongs in Rails, though, so I'd like to try to get a patch in to Rails once we get this worked out. I'd like the rspec-rails matchers to be simple wrappers for rails' assertions wherever possible. Well, I'm not sure if there is a problem with the Rails assertions. In my (albeit limited) experience I haven't yet seen a situation where they couldn't express something during testing. So as you point out, the job of RSpec should just be to expose those APIs within specs in a usable and effective manner. If we discover some limitation that we can't get around, then sure, the upstream assertions will need some work. > I think having three separate matchers would land us in a good spot. Agreed. That's why I added a matcher for each of assert_recognizes, assert_generates, and assert_routing (although so far in practice I've only had to use two of them). > The wrapped rails assertions also accept a hash representing query params, so let's see if we can accommodate that as well: > > get('/something', :ref_id => '1234').should route_to(....) Yes, in my initial implementation I left that out seeing as I haven't yet run into a spec that needed it, but I did have it in mind when I wrote the "get" etc methods (in fact, when I first typed them in I started with 'def get path, options = {}', but then thought, YAGNI, better not add that in until I am sure I need it...) > Something like: > > describe "The router" do > it { should recognize(get('/wiki/foo').as("wiki#show", :id => 'foo') } > it { should generate(get('/wiki/foo').from("wiki#show", :id => 'foo') } > it { should route(get('/wiki/foo').to("wiki#show", :id => 'foo') } > end Yes, the "action#controller" notation is a good idea. I actually added that to the gist that I posted already. Not sure about nesting the get() method inside the matcher though. It seems that in most other places, we use hashes or literal values; eg: something.should do_something(:when => 'always', :how => 'quickly') So, it would be more consistent with existing style to write: it { should recognize(:get => '/wiki/foo').as('wiki#show', :id => 'foo') } But then we lose some of the conciseness I was looking for in my original proposal. In any case we also lose the similarity with controller specs (where "get" is the first thing on the line) which I was also looking for. Nevertheless, your choice of verbs and prepositions work well together; "recognize as", "generate from" and "route to" all read fairly well. Just to clarify, are you suggesting that: - "recognize as" wrap assert_recognizes? - "generate from" wrap assert_generates? - "route to" wrap assert_routing? If so, one misgiving I have is that we still have a unidirectional preposition ("to") being used in conjunction with the bidirectional assertion. An interesting consequence of the language you propose is that the focus of testing changes ie. in the current generator templates, we have: describe FooController do describe 'routing' do it 'recognizes and generates #index' do { :get => 'bar' }.should route_to(:controller => 'bar', :action => 'index') So the focus is on controller actions, and the subject of each 'it' block is a literal hash representing a request to that controller and action. The new language puts the router at the center and the implicit subject of each 'it' block is really the router itself. > That's definitely nice and clean, and it makes it easier to align the names with the rails assertions, which I think adds some value. The output could be formatted something like this: > > The router > should recognize get('/wiki/foo') as wiki#show with :id => 'foo' > should generate get('/wiki/foo') from wiki#show with :id => 'foo' > should route get('/wiki/foo') to wiki#show with :id => 'foo' > > Thoughts? I think it would be nicer to format that as "GET /wiki/foo" (ie. HTTP verb followed by path) rather than embedding the literal text of the "get('/wiki/foo')" method call. In any case, I converted another RESTful resource over to the syntax I mentioned earlier, now using the "controller#action" syntax: describe IssuesController do describe 'routing' do example 'GET /issues' do get('/issues').should map('issues#index') end example 'GET /issues/new' do get('/issues/new').should map('issues#new') end example 'GET /issues/:id' do get('/issues/123').should map('issues#show', :id => '123') end example 'GET /issues/:id/edit' do get('/issues/123/edit').should map('issues#edit', :id => '123') end example 'PUT /issues/:id' do put('/issues/123').should map('issues#update', :id => '123') end example 'DELETE /issues/:id' do delete('/issues/123').should map('issues#destroy', :id => '123') end end end Which, if you really care about conciseness, can be written as: describe IssuesController do describe 'routing' do it { post('/issues').should map('issues#create') } it { get('/issues').should map('issues#index') } it { get('/issues/new').should map('issues#new') } it { get('/issues/123').should map('issues#show', :id => '123') } it { get('/issues/123/edit').should map('issues#edit', :id => '123') } it { put('/issues/123').should map('issues#update', :id => '123') } it { delete('/issues/123').should map('issues#destroy', :id => '123') } end end These get formatted in the spec output as: IssuesController routing GET /issues GET /issues/new GET /issues/:id GET /issues/:id/edit PUT /issues/:id DELETE /issues/:id And: IssuesController routing should map "issues#create" should map "issues#index" should map "issues#new" should map "issues#show" and {:id=>"123"} should map "issues#edit" and {:id=>"123"} should map "issues#update" and {:id=>"123"} should map "issues#destroy" and {:id=>"123"} Respectively. By adding a description method to the matcher (see updated Gist: http://gist.github.com/464081), we can produce: IssuesController routing should map POST /issues as issues#create should map GET /issues as issues#index should map GET /issues/new as issues#new should map GET /issues/123 as issues#show with {:id=>"123"} should map GET /issues/123/edit as issues#edit with {:id=>"123"} should map PUT /issues/123 as issues#update with {:id=>"123"} should map DELETE /issues/123 as issues#destroy with {:id=>"123"} Which IMO looks pretty nice. Cheers, Wincent From thecatwasnot at gmail.com Mon Jul 5 10:52:18 2010 From: thecatwasnot at gmail.com (Pixel) Date: Mon, 5 Jul 2010 09:52:18 -0500 Subject: [rspec-users] Problem specing application layout, missing partial? Message-ID: In an effort to teach myself BDD I'm trying it out. I'm trying to do a simple (should be straightforward) spec on my application.html.haml file first looking for a div tag with the class 'nav' it seems that rspec isn't able to render the app/views/layouts/application.html.haml file. Gist with command/error/backtrace: http://gist.github.com/463978#file_gistfile1.txt $ rspec spec/views/layouts/application.html.haml_spec.rb -b F 1) layouts/application.haml.html displays a navigation area Failure/Error: render "layouts/application.html.haml" Missing partial layouts/application.html with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml, :haml], :formats=>[:html, :text, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json], :locale=>[:en, :en]} in view paths "/home/pixel/Development/code/achieveit.git/app/views", "/home/pixel/Development/code/achieveit.git/vendor/plugins/haml/app/views" # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/actionpack-3.0.0.beta4/lib/action_view/paths.rb:14:in `find' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/actionpack-3.0.0.beta4/lib/action_view/lookup_context.rb:79:in `find' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/actionpack-3.0.0.beta4/lib/action_view/base.rb:186:in `find_template' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/actionpack-3.0.0.beta4/lib/action_view/render/partials.rb:310:in `find_template' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/actionpack-3.0.0.beta4/lib/action_view/render/partials.rb:211:in `render' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/actionpack-3.0.0.beta4/lib/action_view/render/partials.rb:332:in `_render_partial' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/actionpack-3.0.0.beta4/lib/action_view/render/rendering.rb:30:in `render' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/haml-3.0.13/lib/haml/helpers/action_view_mods.rb:13:in `render_with_haml' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/actionpack-3.0.0.beta4/lib/action_view/test_case.rb:100:in `render' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-rails-2.0.0.beta.15/lib/rspec/rails/example/view_example_group.rb:58:in `render' # ./spec/views/layouts/application.html.haml_spec.rb:5:in `block (2 levels) in ' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example.rb:76:in `instance_eval' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example.rb:76:in `block in with_pending_capture' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example.rb:75:in `catch' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example.rb:75:in `with_pending_capture' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example.rb:50:in `block in run' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example.rb:46:in `call' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example.rb:46:in `run' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example_group.rb:186:in `block in run_examples' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example_group.rb:183:in `map' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example_group.rb:183:in `run_examples' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/example_group.rb:174:in `run' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/command_line.rb:41:in `block in run_examples' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/command_line.rb:41:in `each' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/command_line.rb:41:in `inject' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/command_line.rb:41:in `run_examples' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/command_line.rb:24:in `block in run' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/formatters/base_formatter.rb:37:in `block in report' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/formatters/base_formatter.rb:152:in `sync_output' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/formatters/base_formatter.rb:34:in `report' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/command_line.rb:21:in `run' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/runner.rb:46:in `run_in_process' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/runner.rb:37:in `run' # /home/pixel/.rvm/gems/ruby-1.9.2-head at rails3/gems/rspec-core-2.0.0.beta.15/lib/rspec/core/runner.rb:22:in `block in autorun' Finished in 0.28094 seconds 1 example, 1 failure Spec file: http://gist.github.com/463978#file_application.html.haml_spec.rb File under spec: http://gist.github.com/463978#file_application.html.haml Gem list: http://gist.github.com/463978#file_gistfile4.txt The problem may be something simple but several hours of googling haven't helped and I'm at a loss. -Cole -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Mon Jul 5 12:16:57 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 11:16:57 -0500 Subject: [rspec-users] Problem specing application layout, missing partial? In-Reply-To: References: Message-ID: <309A211A-6D3C-4716-880D-9F8069192B1D@gmail.com> On Jul 5, 2010, at 9:52 AM, Pixel wrote: > In an effort to teach myself BDD I'm trying it out. I'm trying to do a simple (should be straightforward) spec on my application.html.haml file first looking for a div tag with the class 'nav' it seems that rspec isn't able to render the app/views/layouts/application.html.haml file. > Gist with command/error/backtrace: http://gist.github.com/463978#file_gistfile1.txt Short version: Don't pass anything to render() in the spec. It'll do the right thing as long as you name the template in the string passed to describe: require "spec_helper" describe "layouts/application.html.haml" do it "displays a navigation area" do render rendered.should have_selector('div#nav') end end Only slightly longer version: There are some confusing things about the render() method in ActionView::Base, which is ultimately what renders the the template. View specs handle this for you by building the hash that Rails' render() is looking for when you don't pass anything to render. In this case, the example above results in the equivalent of: require "spec_helper" describe "layouts/application.html.haml" do it "displays a navigation area" do render :template => "layouts/application.html.haml" rendered.should have_selector('div#nav') end end HTH, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Mon Jul 5 12:18:00 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 11:18:00 -0500 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> Message-ID: <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> On Jul 5, 2010, at 9:04 AM, Wincent Colaiuta wrote: > El 05/07/2010, a las 13:56, David Chelimsky escribi?: > >> Nice overall. Much of the code belongs in Rails, though, so I'd like to try to get a patch in to Rails once we get this worked out. I'd like the rspec-rails matchers to be simple wrappers for rails' assertions wherever possible. > > > Well, I'm not sure if there is a problem with the Rails assertions. Not that there is a problem with them, but all Rails users could benefit from methods like get(path) in their routing tests. Although, now that I think of it, those assertions are available in functional tests, and the http verbs are already defined there. The thing that concerns me the most is the DestinationParser. Even though it seems simple, that's the sort of code that ends up making rspec-rails a rails-dependent maintenance problem. > In my (albeit limited) experience I haven't yet seen a situation where they couldn't express something during testing. So as you point out, the job of RSpec should just be to expose those APIs within specs in a usable and effective manner. If we discover some limitation that we can't get around, then sure, the upstream assertions will need some work. > >> I think having three separate matchers would land us in a good spot. > > Agreed. That's why I added a matcher for each of assert_recognizes, assert_generates, and assert_routing (although so far in practice I've only had to use two of them). > >> The wrapped rails assertions also accept a hash representing query params, so let's see if we can accommodate that as well: >> >> get('/something', :ref_id => '1234').should route_to(....) > > Yes, in my initial implementation I left that out seeing as I haven't yet run into a spec that needed it, but I did have it in mind when I wrote the "get" etc methods (in fact, when I first typed them in I started with 'def get path, options = {}', but then thought, YAGNI, better not add that in until I am sure I need it...) > >> Something like: >> >> describe "The router" do >> it { should recognize(get('/wiki/foo')).as("wiki#show", :id => 'foo') } >> it { should generate(get('/wiki/foo')).from("wiki#show", :id => 'foo') } >> it { should route(get('/wiki/foo')).to("wiki#show", :id => 'foo') } >> end > > Yes, the "action#controller" notation is a good idea. I actually added that to the gist that I posted already. That's where I got it from :) > Not sure about nesting the get() method inside the matcher though. It seems that in most other places, we use hashes or literal values; eg: > > something.should do_something(:when => 'always', :how => 'quickly') > > So, it would be more consistent with existing style to write: > > it { should recognize(:get => '/wiki/foo').as('wiki#show', :id => 'foo') } > > But then we lose some of the conciseness I was looking for in my original proposal. Keep in mind this is for a one-liner (no string passed to it), so it's still far more concise than the previous alternatives. > In any case we also lose the similarity with controller specs (where "get" is the first thing on the line) which I was also looking for. > > Nevertheless, your choice of verbs and prepositions work well together; "recognize as", "generate from" and "route to" all read fairly well. > > Just to clarify, are you suggesting that: > > - "recognize as" wrap assert_recognizes? > - "generate from" wrap assert_generates? > - "route to" wrap assert_routing? > > If so, one misgiving I have is that we still have a unidirectional preposition ("to") being used in conjunction with the bidirectional assertion. Agreed. Not sure what the right verbiage is there. > An interesting consequence of the language you propose is that the focus of testing changes ie. in the current generator templates, we have: > > describe FooController do > describe 'routing' do > it 'recognizes and generates #index' do > { :get => 'bar' }.should route_to(:controller => 'bar', :action => 'index') > > So the focus is on controller actions, and the subject of each 'it' block is a literal hash representing a request to that controller and action. > > The new language puts the router at the center and the implicit subject of each 'it' block is really the router itself. I think that's where it belongs. It's the router that does the routing, not the controller. >> That's definitely nice and clean, and it makes it easier to align the names with the rails assertions, which I think adds some value. The output could be formatted something like this: >> >> The router >> should recognize get('/wiki/foo') as wiki#show with :id => 'foo' >> should generate get('/wiki/foo') from wiki#show with :id => 'foo' >> should route get('/wiki/foo') to wiki#show with :id => 'foo' >> >> Thoughts? > > I think it would be nicer to format that as "GET /wiki/foo" (ie. HTTP verb followed by path) rather than embedding the literal text of the "get('/wiki/foo')" method call. You could still get that by adding a message: it { should recognize(get('/wiki/foo')).as("wiki#show", :id => 'foo'), "recognizes GET /wiki/:id" } Not saying that's any better than the other formats, just that it exists as an option. Slight tangent - one nice thing about 'recognize' as a matcher name is we get this for free: it { should_not recognize(:get => '/wiki/foo') } > In any case, I converted another RESTful resource over to the syntax I mentioned earlier, now using the "controller#action" syntax: > > describe IssuesController do > describe 'routing' do > example 'GET /issues' do > get('/issues').should map('issues#index') > end > > example 'GET /issues/new' do > get('/issues/new').should map('issues#new') > end > > example 'GET /issues/:id' do > get('/issues/123').should map('issues#show', :id => '123') > end > > example 'GET /issues/:id/edit' do > get('/issues/123/edit').should map('issues#edit', :id => '123') > end > > example 'PUT /issues/:id' do > put('/issues/123').should map('issues#update', :id => '123') > end > > example 'DELETE /issues/:id' do > delete('/issues/123').should map('issues#destroy', :id => '123') > end > end > end > > Which, if you really care about conciseness, can be written as: > > describe IssuesController do > describe 'routing' do > it { post('/issues').should map('issues#create') } > it { get('/issues').should map('issues#index') } > it { get('/issues/new').should map('issues#new') } > it { get('/issues/123').should map('issues#show', :id => '123') } > it { get('/issues/123/edit').should map('issues#edit', :id => '123') } > it { put('/issues/123').should map('issues#update', :id => '123') } > it { delete('/issues/123').should map('issues#destroy', :id => '123') } > end > end The point of "it' is that it reads as part of a sentence: describe "something" do it "does something" When we introduced the implicit subject, we got this: describe "something" do it { should do_something } In that form it still reads nicely: "it should do something". In this case, saying "it get post issues should map issues#create" makes me want to cry. We've still got example and specify. In this case, I think specify is the most accurate: describe IssuesController do describe 'routing' do specify { post('/issues').should map('issues#create') } Out loud this is "specify [that a] post [to] /issues should map [to] issues#create". I can live with that tear-free. Except when Brazil gets knocked out of the cup, but that's a different matter. > These get formatted in the spec output as: > > IssuesController > routing > GET /issues > GET /issues/new > GET /issues/:id > GET /issues/:id/edit > PUT /issues/:id > DELETE /issues/:id > > And: > > IssuesController > routing > should map "issues#create" > should map "issues#index" > should map "issues#new" > should map "issues#show" and {:id=>"123"} > should map "issues#edit" and {:id=>"123"} > should map "issues#update" and {:id=>"123"} > should map "issues#destroy" and {:id=>"123"} > > Respectively. By adding a description method to the matcher (see updated Gist: http://gist.github.com/464081), we can produce: > > IssuesController > routing > should map POST /issues as issues#create > should map GET /issues as issues#index > should map GET /issues/new as issues#new > should map GET /issues/123 as issues#show with {:id=>"123"} > should map GET /issues/123/edit as issues#edit with {:id=>"123"} > should map PUT /issues/123 as issues#update with {:id=>"123"} > should map DELETE /issues/123 as issues#destroy with {:id=>"123"} > > Which IMO looks pretty nice. It does, though seeing that last output makes me wonder about the "map/as" verbiage. Seems less clear in this context for some reason. Anybody else besides me and Wincent and Matt want to weigh in here? Cheers, David From win at wincent.com Mon Jul 5 12:58:53 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 5 Jul 2010 18:58:53 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> Message-ID: El 05/07/2010, a las 18:18, David Chelimsky escribi?: > The thing that concerns me the most is the DestinationParser. Even though it seems simple, that's the sort of code that ends up making rspec-rails a rails-dependent maintenance problem. But seeing as we're wrapping Rails assertions we're always going to be vulnerable to upstream changes. We're vulnerable to them right now in the existing route_to matcher. As I see it the purpose of the DestinationParser is to just take the user's parameters in the spec file (a format which we control, designed to make specs read nicely) and put them in a format that assert_(recognizes|generates|routing) expects (a format that the Rails team controls, designed according to their own criteria). If they ever change their format, they'll break thousands of users' specs, whether or not we have a "DestinationParser". > Slight tangent - one nice thing about 'recognize' as a matcher name is we get this for free: > > it { should_not recognize(:get => '/wiki/foo') } True, but with "get()" we can already do: it { get('/wiki/foo').should_not be_routable } Which is effectively the same isn't it? > The point of "it' is that it reads as part of a sentence: > > describe "something" do > it "does something" > > When we introduced the implicit subject, we got this: > > describe "something" do > it { should do_something } > > In that form it still reads nicely: "it should do something". > > In this case, saying "it get post issues should map issues#create" makes me want to cry. Yes, I know what you mean. > We've still got example and specify. Knew about example, had forgotten about specify... now that one goes a loooooong way back doesn't it? >> IssuesController >> routing >> should map POST /issues as issues#create >> should map GET /issues as issues#index >> should map GET /issues/new as issues#new >> should map GET /issues/123 as issues#show with {:id=>"123"} >> should map GET /issues/123/edit as issues#edit with {:id=>"123"} >> should map PUT /issues/123 as issues#update with {:id=>"123"} >> should map DELETE /issues/123 as issues#destroy with {:id=>"123"} >> >> Which IMO looks pretty nice. > > It does, though seeing that last output makes me wonder about the "map/as" verbiage. Seems less clear in this context for some reason. I think it would read quite nicely as "should map something _to_ something", but that puts us back in the old "uni-directional" word for "bi-directional" relationship problem. I was trying to have: - "should map X to Y" correspond to map_to/assert_recognizes - "should map X from Y" correspond to map_from/assert_generates - "should map X as Y" correspond to map/assert_routing One possibility that I've been toying with is substituting "route" for "map" here, but "route_to" clashes with the existing "route_to" matcher in RSpec, and I am not sure that it buys us anything anyway... As you said earlier on, language is hard... > Anybody else besides me and Wincent and Matt want to weigh in here? Oops, does that mean I should stop posting? ;-) Cheers, Wincent From dchelimsky at gmail.com Mon Jul 5 13:17:54 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 12:17:54 -0500 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> Message-ID: <222ED329-5740-4C9C-8D90-2E0730C9C534@gmail.com> On Jul 5, 2010, at 11:58 AM, Wincent Colaiuta wrote: > El 05/07/2010, a las 18:18, David Chelimsky escribi?: > >> The thing that concerns me the most is the DestinationParser. Even though it seems simple, that's the sort of code that ends up making rspec-rails a rails-dependent maintenance problem. > > But seeing as we're wrapping Rails assertions we're always going to be vulnerable to upstream changes. We're vulnerable to them right now in the existing route_to matcher. Sort of. What route_to relies on is a published API. If Rails changes the meaning of assert_routing, that will impact all Rails users, not just rspec users. This is a hot-button issue for me because relying on anything but published APIs has led to frantic day-after-rails-release rspec-rails releases in the past. Probably not really in an issue in this case, though. After looking at it some more, DestinationParser isn't really relying on any code in Rails, its relying on consistency in the routing API going forward. i.e. if Rails stops supporting this format, DestinationParser won't break, but the concept won't align correctly with Rails any longer. In this case, I think we're OK. > As I see it the purpose of the DestinationParser is to just take the user's parameters in the spec file (a format which we control, designed to make specs read nicely) and put them in a format that assert_(recognizes|generates|routing) expects (a format that the Rails team controls, designed according to their own criteria). If they ever change their format, they'll break thousands of users' specs, whether or not we have a "DestinationParser". Right :) >> Slight tangent - one nice thing about 'recognize' as a matcher name is we get this for free: >> >> it { should_not recognize(:get => '/wiki/foo') } > > True, but with "get()" we can already do: > > it { get('/wiki/foo').should_not be_routable } > > Which is effectively the same isn't it? Effectively, yes, but I'm liking "recognize" better than "be_routable". >> The point of "it' is that it reads as part of a sentence: >> >> describe "something" do >> it "does something" >> >> When we introduced the implicit subject, we got this: >> >> describe "something" do >> it { should do_something } >> >> In that form it still reads nicely: "it should do something". >> >> In this case, saying "it get post issues should map issues#create" makes me want to cry. > > Yes, I know what you mean. > >> We've still got example and specify. > > Knew about example, had forgotten about specify... now that one goes a loooooong way back doesn't it? > >>> IssuesController >>> routing >>> should map POST /issues as issues#create >>> should map GET /issues as issues#index >>> should map GET /issues/new as issues#new >>> should map GET /issues/123 as issues#show with {:id=>"123"} >>> should map GET /issues/123/edit as issues#edit with {:id=>"123"} >>> should map PUT /issues/123 as issues#update with {:id=>"123"} >>> should map DELETE /issues/123 as issues#destroy with {:id=>"123"} >>> >>> Which IMO looks pretty nice. >> >> It does, though seeing that last output makes me wonder about the "map/as" verbiage. Seems less clear in this context for some reason. > > I think it would read quite nicely as "should map something _to_ something", but that puts us back in the old "uni-directional" word for "bi-directional" relationship problem. I was trying to have: > > - "should map X to Y" correspond to map_to/assert_recognizes > - "should map X from Y" correspond to map_from/assert_generates > - "should map X as Y" correspond to map/assert_routing > One possibility that I've been toying with is substituting "route" for "map" here, but "route_to" clashes with the existing "route_to" matcher in RSpec, and I am not sure that it buys us anything anyway... I think "map" is working for me in this context. The word "route" suggests "take a path and route it to a destination", whereas "map" suggests "these two things are related, so map one to the other", at which point [to|from|as] provide more context as to the nature of the relationship. > As you said earlier on, language is hard... >> Anybody else besides me and Wincent and Matt want to weigh in here? > > Oops, does that mean I should stop posting? ;-) Immediately! Srsly, not a bit - just looking for other voices. Cheers, David From thecatwasnot at gmail.com Mon Jul 5 13:21:39 2010 From: thecatwasnot at gmail.com (Pixel) Date: Mon, 5 Jul 2010 12:21:39 -0500 Subject: [rspec-users] Problem specing application layout, missing partial? In-Reply-To: <309A211A-6D3C-4716-880D-9F8069192B1D@gmail.com> References: <309A211A-6D3C-4716-880D-9F8069192B1D@gmail.com> Message-ID: On Mon, Jul 5, 2010 at 11:16 AM, David Chelimsky wrote: > On Jul 5, 2010, at 9:52 AM, Pixel wrote: > > In an effort to teach myself BDD I'm trying it out. I'm trying to do a > simple (should be straightforward) spec on my application.html.haml file > first looking for a div tag with the class 'nav' it seems that rspec isn't > able to render the app/views/layouts/application.html.haml file. > Gist with command/error/backtrace: > http://gist.github.com/463978#file_gistfile1.txt > > > Short version: > > Don't pass anything to render() in the spec. It'll do the right thing as > long as you name the template in the string passed to describe: > > require "spec_helper" > > describe "layouts/application.html.haml" do > it "displays a navigation area" do > render > rendered.should have_selector('div#nav') > end > end > Of course it helps when I write out the file name correctly in the describe line, so that rspec can build the correct call. Woops! Thanks for your help and patience David, much appreciated. - Cole -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Mon Jul 5 13:35:00 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 12:35:00 -0500 Subject: [rspec-users] Problem specing application layout, missing partial? In-Reply-To: References: <309A211A-6D3C-4716-880D-9F8069192B1D@gmail.com> Message-ID: On Jul 5, 2010, at 12:21 PM, Pixel wrote: > On Mon, Jul 5, 2010 at 11:16 AM, David Chelimsky wrote: > On Jul 5, 2010, at 9:52 AM, Pixel wrote: > >> In an effort to teach myself BDD I'm trying it out. I'm trying to do a simple (should be straightforward) spec on my application.html.haml file first looking for a div tag with the class 'nav' it seems that rspec isn't able to render the app/views/layouts/application.html.haml file. >> Gist with command/error/backtrace: http://gist.github.com/463978#file_gistfile1.txt > > Short version: > > Don't pass anything to render() in the spec. It'll do the right thing as long as you name the template in the string passed to describe: > > require "spec_helper" > > describe "layouts/application.html.haml" do > it "displays a navigation area" do > render > rendered.should have_selector('div#nav') > end > end > > Of course it helps when I write out the file name correctly in the describe line, so that rspec can build the correct call. Woops! Thanks for your help and patience David, much appreciated. Yes, it turns out that computers are not great interpreters :) Happy to help. Cheers, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Mon Jul 5 13:38:05 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 12:38:05 -0500 Subject: [rspec-users] Loading problem with engine extending ActionController::Base In-Reply-To: <201007032340.00828.michael@schuerig.de> References: <201007032234.42820.michael@schuerig.de> <203A8E17-F779-4F50-A2E2-BA2FC3B4E6BB@gmail.com> <201007032340.00828.michael@schuerig.de> Message-ID: <1A6C67D8-8E4C-47DD-98A6-5D93E775DA4D@gmail.com> On Jul 3, 2010, at 4:40 PM, Michael Schuerig wrote: > On Saturday 03 July 2010, David Chelimsky wrote: >> On Jul 3, 2010, at 3:34 PM, Michael Schuerig wrote: > > [double loading of Rails framework classes] >>> require File.dirname(__FILE__) + "/../config/environment" unless >>> defined?(Rails) >> >> This is from an old version of the spec_helper. Be sure to follow the >> post-install instructions (that's what they're there for) and run >> "script/rails generate rspec:install". > > Indeed, you're right. I compared old and new visually (only) and didn't > notice the difference. As I have some stuff in spec_helper.rb, I don't > like to overwrite it. > >> The newer generated spec_helper uses File.expand_path for this >> require, so it doesn't load the file a second time. I believe that >> will fix this issue for you. > > Unfortunately and surprisingly not. Did you try both 'rake spec' and 'bundle exec rspec spec'? > I'm using > > ruby 1.8.7 (2010-06-23 patchlevel 299) [x86_64-linux] > > in case that makes a difference. > > I can work around this by including the required extension explicitly in > ApplicationController, of course. Yeah, but who wants to do that! Would you do me a favor and raise this as an issue in http://github.com/rspec/rspec-rails/issues? I won't be able to address this for a bit, and that's the best way to ensure it stays on the radar. Cheers, David From win at wincent.com Mon Jul 5 13:18:51 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 5 Jul 2010 19:18:51 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> Message-ID: <20B5B99E-5D0B-4F41-9FCF-C23E30E5B4B3@wincent.com> El 05/07/2010, a las 18:58, Wincent Colaiuta escribi?: > El 05/07/2010, a las 18:18, David Chelimsky escribi?: > >> Slight tangent - one nice thing about 'recognize' as a matcher name is we get this for free: >> >> it { should_not recognize(:get => '/wiki/foo') } > > True, but with "get()" we can already do: > > it { get('/wiki/foo').should_not be_routable } > > Which is effectively the same isn't it? Bah, I take that back. Just looked and I see that the "be_routable" matcher expects its params to be of the form: { :method => 'path' } And get() is giving it params of the form: { :method => :get, :path => 'path' } Cheers, Wincent From ashley.moran at patchspace.co.uk Mon Jul 5 13:51:17 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Mon, 5 Jul 2010 18:51:17 +0100 Subject: [rspec-users] [ANN] ShRUG 8, Mon July 12th: Introduction to RSpec Message-ID: Hi all Reposting this for the benefit of anyone who may be able to attend but wouldn't normally see ShRUG announcements. ShRUG is the Sheffield (UK) Ruby User Group. ShRUG July 2010 is now confirmed. Ashley Moran (that's me) of PatchSpace Ltd (that's also me, really) will be running an introduction to RSpec, a powerful and mature BDD/testing library for Ruby*. No RSpec or unit testing experience is necessary, as we will be starting from first principles, but knowing basic Ruby will help. We're at the new GIST Lab in Sheffield, which is part of the Workstation. Turn up at 6.30pm for a 7.00-9.00pm presentation. Followed by general pubbage activity as usual. Details and map available on the ShRUG site: http://shrug.org/meetings/shrug-8/ You can keep updated via our Twitter account too: http://twitter.com/shruggers If you're going please sign up for a ticket here: http://shrug8.eventbrite.com/ You don't have to get a ticket, but we like to know who's planning to turn up to predict numbers. See you there! Cheers Ash BTW - We're always looking for people to run sessions (short or long). If you have an idea please drop me a line. * You all know that :) This announcement was originally prepared for the local mailing lists... -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From win at wincent.com Mon Jul 5 13:38:09 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 5 Jul 2010 19:38:09 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <222ED329-5740-4C9C-8D90-2E0730C9C534@gmail.com> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> <222ED329-5740-4C9C-8D90-2E0730C9C534@gmail.com> Message-ID: <6697E395-4F27-4B39-8EF3-12D76107C76D@wincent.com> El 05/07/2010, a las 19:17, David Chelimsky escribi?: > On Jul 5, 2010, at 11:58 AM, Wincent Colaiuta wrote: > >> El 05/07/2010, a las 18:18, David Chelimsky escribi?: >> >>> The thing that concerns me the most is the DestinationParser. Even though it seems simple, that's the sort of code that ends up making rspec-rails a rails-dependent maintenance problem. >> >> But seeing as we're wrapping Rails assertions we're always going to be vulnerable to upstream changes. We're vulnerable to them right now in the existing route_to matcher. > > Sort of. What route_to relies on is a published API. If Rails changes the meaning of assert_routing, that will impact all Rails users, not just rspec users. > > This is a hot-button issue for me because relying on anything but published APIs has led to frantic day-after-rails-release rspec-rails releases in the past. Probably not really in an issue in this case, though. After looking at it some more, DestinationParser isn't really relying on any code in Rails, its relying on consistency in the routing API going forward. i.e. if Rails stops supporting this format, DestinationParser won't break, but the concept won't align correctly with Rails any longer. In this case, I think we're OK. Yes, it's not doing any more than "route_to" is already doing (ie. preparing the parameters to be fed into "assert_routing"). It may have looked scarier than it was; I just wanted to stick it in a module so as not to repeat the code in each of the three matchers. >>> Anybody else besides me and Wincent and Matt want to weigh in here? >> >> Oops, does that mean I should stop posting? ;-) > > Immediately! > > Srsly, not a bit - just looking for other voices. Yes, would be good. To be honest, with a change like this (involving interface design), I think slowly is the way to go. Cheers, Wincent From dchelimsky at gmail.com Mon Jul 5 14:01:50 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 13:01:50 -0500 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <6697E395-4F27-4B39-8EF3-12D76107C76D@wincent.com> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> <222ED329-5740-4C9C-8D90-2E0730C9C534@gmail.com> <6697E395-4F27-4B39-8EF3-12D76107C76D@wincent.com> Message-ID: On Jul 5, 2010, at 12:38 PM, Wincent Colaiuta wrote: > El 05/07/2010, a las 19:17, David Chelimsky escribi?: > >> On Jul 5, 2010, at 11:58 AM, Wincent Colaiuta wrote: >> >>> El 05/07/2010, a las 18:18, David Chelimsky escribi?: >>> >>>> The thing that concerns me the most is the DestinationParser. Even though it seems simple, that's the sort of code that ends up making rspec-rails a rails-dependent maintenance problem. >>> >>> But seeing as we're wrapping Rails assertions we're always going to be vulnerable to upstream changes. We're vulnerable to them right now in the existing route_to matcher. >> >> Sort of. What route_to relies on is a published API. If Rails changes the meaning of assert_routing, that will impact all Rails users, not just rspec users. >> >> This is a hot-button issue for me because relying on anything but published APIs has led to frantic day-after-rails-release rspec-rails releases in the past. Probably not really in an issue in this case, though. After looking at it some more, DestinationParser isn't really relying on any code in Rails, its relying on consistency in the routing API going forward. i.e. if Rails stops supporting this format, DestinationParser won't break, but the concept won't align correctly with Rails any longer. In this case, I think we're OK. > > Yes, it's not doing any more than "route_to" is already doing (ie. preparing the parameters to be fed into "assert_routing"). It may have looked scarier than it was; I just wanted to stick it in a module so as not to repeat the code in each of the three matchers. > >>>> Anybody else besides me and Wincent and Matt want to weigh in here? >>> >>> Oops, does that mean I should stop posting? ;-) >> >> Immediately! >> >> Srsly, not a bit - just looking for other voices. > > Yes, would be good. To be honest, with a change like this (involving interface design), I think slowly is the way to go. Agreed, but there is a bit of pressure here - we don't have separate wrapper matchers assert_recognizes or assert_generates, and I want to ship 2.0.0 with a solution for that. Given that rails 3 should have a release candidate some time soon, there's no time like the present :) From rjharmon0316 at yahoo.com Mon Jul 5 14:18:48 2010 From: rjharmon0316 at yahoo.com (Randy Harmon) Date: Mon, 05 Jul 2010 11:18:48 -0700 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> Message-ID: <4C322208.2060307@yahoo.com> I'll chime in, having contributed some of the mess at hand. Good things I'm seeing between current route helpers and proposals include: * The router being at the center of what's being tested * Similarity of specs to other conventions * Ability to specify bi-directional routing behavior (by default, since it's most common) * Clear indication that a route spec is in fact testing both recognition and generation * Easily specify negative routes (PUT /foo doesn't route). * Include testing of URL helpers * DRY, but not at the expense of clarity I'm uncertain about the need to easily specify one-directional routes. While in theory it sounds fine, I don't understand why you'd want to specify either a route that isn't recognized (why bother routing it, in this case?) or one that doesn't generate the given path with url_for() (does it generate some other path instead?). I didn't see any examples of its usage in the gist, but I did see a lot of code for it... YAGNI?? or, if I were able to understand the motivation better, maybe this would make more sense to me. Randy On 7/5/10 9:18 AM, David Chelimsky wrote: > On Jul 5, 2010, at 9:04 AM, Wincent Colaiuta wrote: > > >> El 05/07/2010, a las 13:56, David Chelimsky escribi?: >> >> >>> Nice overall. Much of the code belongs in Rails, though, so I'd like to try to get a patch in to Rails once we get this worked out. I'd like the rspec-rails matchers to be simple wrappers for rails' assertions wherever possible. >>> >> >> Well, I'm not sure if there is a problem with the Rails assertions. >> > Not that there is a problem with them, but all Rails users could benefit from methods like get(path) in their routing tests. Although, now that I think of it, those assertions are available in functional tests, and the http verbs are already defined there. > > The thing that concerns me the most is the DestinationParser. Even though it seems simple, that's the sort of code that ends up making rspec-rails a rails-dependent maintenance problem. > > >> In my (albeit limited) experience I haven't yet seen a situation where they couldn't express something during testing. So as you point out, the job of RSpec should just be to expose those APIs within specs in a usable and effective manner. If we discover some limitation that we can't get around, then sure, the upstream assertions will need some work. >> >> >>> I think having three separate matchers would land us in a good spot. >>> >> Agreed. That's why I added a matcher for each of assert_recognizes, assert_generates, and assert_routing (although so far in practice I've only had to use two of them). >> >> >>> The wrapped rails assertions also accept a hash representing query params, so let's see if we can accommodate that as well: >>> >>> get('/something', :ref_id => '1234').should route_to(....) >>> >> Yes, in my initial implementation I left that out seeing as I haven't yet run into a spec that needed it, but I did have it in mind when I wrote the "get" etc methods (in fact, when I first typed them in I started with 'def get path, options = {}', but then thought, YAGNI, better not add that in until I am sure I need it...) >> >> >>> Something like: >>> >>> describe "The router" do >>> it { should recognize(get('/wiki/foo')).as("wiki#show", :id => 'foo') } >>> it { should generate(get('/wiki/foo')).from("wiki#show", :id => 'foo') } >>> it { should route(get('/wiki/foo')).to("wiki#show", :id => 'foo') } >>> end >>> >> Yes, the "action#controller" notation is a good idea. I actually added that to the gist that I posted already. >> > That's where I got it from :) > > >> Not sure about nesting the get() method inside the matcher though. It seems that in most other places, we use hashes or literal values; eg: >> >> something.should do_something(:when => 'always', :how => 'quickly') >> >> So, it would be more consistent with existing style to write: >> >> it { should recognize(:get => '/wiki/foo').as('wiki#show', :id => 'foo') } >> >> But then we lose some of the conciseness I was looking for in my original proposal. >> > Keep in mind this is for a one-liner (no string passed to it), so it's still far more concise than the previous alternatives. > > >> In any case we also lose the similarity with controller specs (where "get" is the first thing on the line) which I was also looking for. >> >> Nevertheless, your choice of verbs and prepositions work well together; "recognize as", "generate from" and "route to" all read fairly well. >> >> Just to clarify, are you suggesting that: >> >> - "recognize as" wrap assert_recognizes? >> - "generate from" wrap assert_generates? >> - "route to" wrap assert_routing? >> >> If so, one misgiving I have is that we still have a unidirectional preposition ("to") being used in conjunction with the bidirectional assertion. >> > Agreed. Not sure what the right verbiage is there. > > >> An interesting consequence of the language you propose is that the focus of testing changes ie. in the current generator templates, we have: >> >> describe FooController do >> describe 'routing' do >> it 'recognizes and generates #index' do >> { :get => 'bar' }.should route_to(:controller => 'bar', :action => 'index') >> >> So the focus is on controller actions, and the subject of each 'it' block is a literal hash representing a request to that controller and action. >> >> The new language puts the router at the center and the implicit subject of each 'it' block is really the router itself. >> > I think that's where it belongs. It's the router that does the routing, not the controller. > > >>> That's definitely nice and clean, and it makes it easier to align the names with the rails assertions, which I think adds some value. The output could be formatted something like this: >>> >>> The router >>> should recognize get('/wiki/foo') as wiki#show with :id => 'foo' >>> should generate get('/wiki/foo') from wiki#show with :id => 'foo' >>> should route get('/wiki/foo') to wiki#show with :id => 'foo' >>> >>> Thoughts? >>> >> I think it would be nicer to format that as "GET /wiki/foo" (ie. HTTP verb followed by path) rather than embedding the literal text of the "get('/wiki/foo')" method call. >> > You could still get that by adding a message: > > it { should recognize(get('/wiki/foo')).as("wiki#show", :id => 'foo'), "recognizes GET /wiki/:id" } > > Not saying that's any better than the other formats, just that it exists as an option. > > Slight tangent - one nice thing about 'recognize' as a matcher name is we get this for free: > > it { should_not recognize(:get => '/wiki/foo') } > > >> In any case, I converted another RESTful resource over to the syntax I mentioned earlier, now using the "controller#action" syntax: >> >> describe IssuesController do >> describe 'routing' do >> example 'GET /issues' do >> get('/issues').should map('issues#index') >> end >> >> example 'GET /issues/new' do >> get('/issues/new').should map('issues#new') >> end >> >> example 'GET /issues/:id' do >> get('/issues/123').should map('issues#show', :id => '123') >> end >> >> example 'GET /issues/:id/edit' do >> get('/issues/123/edit').should map('issues#edit', :id => '123') >> end >> >> example 'PUT /issues/:id' do >> put('/issues/123').should map('issues#update', :id => '123') >> end >> >> example 'DELETE /issues/:id' do >> delete('/issues/123').should map('issues#destroy', :id => '123') >> end >> end >> end >> >> Which, if you really care about conciseness, can be written as: >> >> describe IssuesController do >> describe 'routing' do >> it { post('/issues').should map('issues#create') } >> it { get('/issues').should map('issues#index') } >> it { get('/issues/new').should map('issues#new') } >> it { get('/issues/123').should map('issues#show', :id => '123') } >> it { get('/issues/123/edit').should map('issues#edit', :id => '123') } >> it { put('/issues/123').should map('issues#update', :id => '123') } >> it { delete('/issues/123').should map('issues#destroy', :id => '123') } >> end >> end >> > The point of "it' is that it reads as part of a sentence: > > describe "something" do > it "does something" > > When we introduced the implicit subject, we got this: > > describe "something" do > it { should do_something } > > In that form it still reads nicely: "it should do something". > > In this case, saying "it get post issues should map issues#create" makes me want to cry. We've still got example and specify. In this case, I think specify is the most accurate: > > describe IssuesController do > describe 'routing' do > specify { post('/issues').should map('issues#create') } > > Out loud this is "specify [that a] post [to] /issues should map [to] issues#create". I can live with that tear-free. Except when Brazil gets knocked out of the cup, but that's a different matter. > > >> These get formatted in the spec output as: >> >> IssuesController >> routing >> GET /issues >> GET /issues/new >> GET /issues/:id >> GET /issues/:id/edit >> PUT /issues/:id >> DELETE /issues/:id >> >> And: >> >> IssuesController >> routing >> should map "issues#create" >> should map "issues#index" >> should map "issues#new" >> should map "issues#show" and {:id=>"123"} >> should map "issues#edit" and {:id=>"123"} >> should map "issues#update" and {:id=>"123"} >> should map "issues#destroy" and {:id=>"123"} >> >> Respectively. By adding a description method to the matcher (see updated Gist: http://gist.github.com/464081), we can produce: >> >> IssuesController >> routing >> should map POST /issues as issues#create >> should map GET /issues as issues#index >> should map GET /issues/new as issues#new >> should map GET /issues/123 as issues#show with {:id=>"123"} >> should map GET /issues/123/edit as issues#edit with {:id=>"123"} >> should map PUT /issues/123 as issues#update with {:id=>"123"} >> should map DELETE /issues/123 as issues#destroy with {:id=>"123"} >> >> Which IMO looks pretty nice. >> > It does, though seeing that last output makes me wonder about the "map/as" verbiage. Seems less clear in this context for some reason. > > Anybody else besides me and Wincent and Matt want to weigh in here? > > Cheers, > David > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > > From rjharmon0316 at yahoo.com Mon Jul 5 14:40:45 2010 From: rjharmon0316 at yahoo.com (Randy Harmon) Date: Mon, 05 Jul 2010 11:40:45 -0700 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> Message-ID: <4C32272D.8080308@yahoo.com> On 7/5/10 2:14 AM, Matt Wynne wrote: > Seems like progress. One thought: Why not use a macro-style syntax to eliminate the boring boilerplate call to #it / #example and generate examples instead? I thought this was an insightful comment. Riffing on that, I get what clearly becomes a DSL along the lines of the following: describe_routes do # method of a controller spec describe "GET /foo" recognizes "GET /foo" # redundant? ignores "PUT /foo" formats [ :html, :json ], :not => [ :xml, :pdf ] generated_from "controller#action", :args => ijef helper :action_controller_path end end You could possibly mix and match some of these, like with multiple "recognizes". Some of these assertive verbs could certainly be optimized too. And, at risk of being promoted to Captain Obvious, I'll point out that the examples generated from these declarations can be crystal clear in their phrasing because the DSL is.. well, more specific to the domain. I'm not sure how to honor the one-directional requirement, but if there are use-cases, I think we could express that case in this DSL and specify the expected outcomes. Of course, there's more than one way to do it. Randy From rjharmon0316 at yahoo.com Mon Jul 5 15:00:45 2010 From: rjharmon0316 at yahoo.com (Randy Harmon) Date: Mon, 05 Jul 2010 12:00:45 -0700 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> <4C322208.2060307@yahoo.com> Message-ID: <4C322BDD.1070804@yahoo.com> David Chelimsky wrote: > ps - I moved your post to the bottom - please bottom/inline post > instead of top-posting (http://idallen.com/topposting.html). Sorry, perhaps I should have deleted most of the quotey bits, since I was replying very generally to the thread. > Check out these two threads: > > http://groups.google.com/group/rspec/browse_thread/thread/9ac4ff6f3bac8423 > http://groups.google.com/group/rspec/browse_thread/thread/4775eaa9b8b3c25f > > Both of them were, coincidentally, started independently and with a day or two of this thread :) > I don't think I understand the core of these two problems - nesting isn't something I've dealt with much. Are they both nested issues, and/or is there a distinction between the two problems? It seems to me that Rails' own assertions aren't able to test these well because the route generation itself is suboptimal. Or does that characterization reveal my lack of understanding? Randy From win at wincent.com Mon Jul 5 15:31:24 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 5 Jul 2010 21:31:24 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <4C322BDD.1070804@yahoo.com> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> <4C322208.2060307@yahoo.com> <4C322BDD.1070804@yahoo.com> Message-ID: <9E0B2B2E-ACC9-4281-B68D-DF23EEED9497@wincent.com> El 05/07/2010, a las 21:00, Randy Harmon escribi?: > David Chelimsky wrote: >> Check out these two threads: >> >> http://groups.google.com/group/rspec/browse_thread/thread/9ac4ff6f3bac8423 >> http://groups.google.com/group/rspec/browse_thread/thread/4775eaa9b8b3c25f >> >> Both of them were, coincidentally, started independently and with a day or two of this thread :) >> > I don't think I understand the core of these two problems - nesting > isn't something I've dealt with much. Are they both nested issues, > and/or is there a distinction between the two problems? It seems to me > that Rails' own assertions aren't able to test these well because the > route generation itself is suboptimal. Or does that characterization > reveal my lack of understanding? I have nothing intelligent to say on this just yet, but I have to do some nested routing specs in my current work, so I should be able to spend some time figuring it out tomorrow. Cheers, Wincent From trev at trevreport.org Mon Jul 5 15:59:34 2010 From: trev at trevreport.org (Lalish-Menagh, Trevor) Date: Mon, 5 Jul 2010 15:59:34 -0400 Subject: [rspec-users] Possible improvements to routing spec API Message-ID: OK, I will chime in here, since I think I might have opened up this can of worms. :) I agree with David that we should stick with wrapping the Rails public APIs. That is: assert_generates, assert_recognizes, and assert_routing (http://edgeapi.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html). OK, here is my thoughts on a format: http://gist.github.com/464636 I want it to be readable in English, so let's try: describe "routing" do specify "days#index" do route get('/days').should generate 'days#index' # wraps assert_generates end end specify [that the] route [path] get('/days') should generate [the options] 'days#index' OK! Next: describe "routing" do specify "days#index" do routing 'days#index'.should recognize get('/days') # wraps assert_recognizes end end specify [that the] route [options] 'days#index' should recognize [the path] get('/days') (Might need some work... but it is uniform). Next: describe "routing" do specify "days#index" do route get('/days').should be 'days#index' # wraps assert_routing end end specify [that the] route [path] get('/days') should be [the options] 'days#index' Finally, this makes nested routes (my original issue) look nice: describe "routing" do specify "days#index" do route 'days#index'.should recognize get('/students/1/days') with :student_id => '1' end end specify [that the] route [options] 'days#index' should recognize [the path] get('/students/1/days') with [extras] :student_id => '1' You could also write out the options longhand to include the extras, but I think this is too ugly: describe "routing" do specify "days#index" do route {:controller => 'days', :action => 'index', :student_id => '1'}.should recognize ('/students/1/days') end end specify [that the] route [options] {:controller => 'days', :action => 'index', :student_id => '1'} should recognize [the path] ('/students/1/days') What do you think? Trevor From win at wincent.com Mon Jul 5 15:40:20 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 5 Jul 2010 21:40:20 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <4C322208.2060307@yahoo.com> References: <95AEE895-1159-4221-B130-0230A2E1B61F@mattwynne.net> <21F4EB4C-6F32-4DBA-88E1-710A6FA2EE29@gmail.com> <5BC213D0-EB11-4983-987B-0A1ED43F4E4B@gmail.com> <4C322208.2060307@yahoo.com> Message-ID: El 05/07/2010, a las 20:18, Randy Harmon escribi?: > I'm uncertain about the need to easily specify one-directional routes. > While in theory it sounds fine, I don't understand why you'd want to > specify either a route that isn't recognized (why bother routing it, in > this case?) or one that doesn't generate the given path with url_for() > (does it generate some other path instead?). Well, I find that most routes map in both directions (ie. basically anything that is specified using "resource" in the config/routes.rb file) but from time to time I find non-resource routes that map only one way (ie. are routable, but url_for won't necessarily generate what you want). Mostly they seem to be routes declared with "match" like this one: resource :posts match '/posts/page/:page' => 'posts#index', :as => 'paginated_posts' You can see here how the mapping doesn't work out the same in both directions: - recognition: '/posts/page/2' is recognized as 'posts#index' with :page => '2' - generation: 'posts#index' with :page => '2' generates '/posts?page=2' Sometimes they can be reorganized so that they _do_ map in both directions; eg: resources :posts do collection do get 'page/:page' => 'posts#index' end end With that change, Rails does know how to do the reverse mapping. But then there are ones which, as far as I know, can't be reorganized in that way; here's one example from my current app: # the resource resource :links # the shortcut to the links#show action match 'l/:id' => 'links#show' According to my experiments, the Rails routing assertions will say that URLs like 'l/foo' are routable, but won't generate in reverse. So there's a case for "assert_recognizes"/"map_to", for sure. I agree with you that it doesn't make much sense to specify an unrecognizable route, but I guess it is conceivable that you could have routes that were recognizable in one direction, but only generated if fed a different set of parameters. So you'd need to test them using a pair of "map_from"/"map_to" or "assert_generates"/"assert_recognizes". Cheers, Wincent From michael at schuerig.de Mon Jul 5 16:21:22 2010 From: michael at schuerig.de (Michael Schuerig) Date: Mon, 5 Jul 2010 22:21:22 +0200 Subject: [rspec-users] Loading problem with engine extending ActionController::Base In-Reply-To: <1A6C67D8-8E4C-47DD-98A6-5D93E775DA4D@gmail.com> References: <201007032234.42820.michael@schuerig.de> <201007032340.00828.michael@schuerig.de> <1A6C67D8-8E4C-47DD-98A6-5D93E775DA4D@gmail.com> Message-ID: <201007052221.23037.michael@schuerig.de> On Monday 05 July 2010, David Chelimsky wrote: > On Jul 3, 2010, at 4:40 PM, Michael Schuerig wrote: > > On Saturday 03 July 2010, David Chelimsky wrote: > >> On Jul 3, 2010, at 3:34 PM, Michael Schuerig wrote: > > [double loading of Rails framework classes] > > > >>> require File.dirname(__FILE__) + "/../config/environment" unless > >>> defined?(Rails) > >> > >> This is from an old version of the spec_helper. Be sure to follow > >> the post-install instructions (that's what they're there for) and > >> run "script/rails generate rspec:install". > > > > Indeed, you're right. I compared old and new visually (only) and > > didn't notice the difference. As I have some stuff in > > spec_helper.rb, I don't like to overwrite it. > > > >> The newer generated spec_helper uses File.expand_path for this > >> require, so it doesn't load the file a second time. I believe that > >> will fix this issue for you. > > > > Unfortunately and surprisingly not. > > Did you try both 'rake spec' and 'bundle exec rspec spec'? bundle exec rspec spec does not make a difference. > Would you do me a favor and raise > this as an issue in http://github.com/rspec/rspec-rails/issues? I > won't be able to address this for a bit, and that's the best way to > ensure it stays on the radar. There you go: http://github.com/rspec/rspec-rails/issues/#issue/118 Michael -- Michael Schuerig mailto:michael at schuerig.de http://www.schuerig.de/michael/ From dchelimsky at gmail.com Mon Jul 5 16:26:18 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 5 Jul 2010 15:26:18 -0500 Subject: [rspec-users] [Rails] Stubbed static methods are bleeding over into other specs and making them fail In-Reply-To: References: Message-ID: <2F30C790-F219-4DD4-8932-8238E66C752D@gmail.com> On Jul 2, 2010, at 7:25 PM, Patrick Gannon wrote: > Hi all, > > I'm having a problem where stubbed static methods aren't properly becoming "unstubbed". I have tried manually unstubbing them, but it still doesn't work. > > Spec is as follows: > > it "creates user accounts for unknown users" do > Notification.stub(:deliver_routed) > User.should_receive(:create).with({:email => "sally at etestflight.com"}) > User.should_receive(:create).with({:email => "joe at etestflight.com"}) > User.stub!(:find_by_email).with("sally at etestflight.com") { nil } > User.stub!(:find_by_email).with("joe at etestflight.com") { nil } > User.stub!(:find_by_email).with("bill at etestflight.com") { User.new } > > begin > post :route, :id => "37", :email_addresses => "sally at etestflight.com, joe at etestflight.com, bill at etestflight.com" > ensure > User.unstub! :find_by_email > #User.unstub! :method_missing > User.rspec_reset > end > end > > It will pass, but then another spec fails with: "undefined method `find_by_email' for Object:Class". The other spec passes when I create a database User and rely on the real definition of User.find_by_email (defined by method_missing in MongoMapper's Document module) in this spec instead of stubbing out the calls to find_by_email. As you can see, I tried calling "unstub!" on find_by_email, and calling rspec_reset, and it doesn't make any difference (other spec still fails). I even tried un-stubbing method_missing (since that's what defines the real find_by_email) and it complains that that was never stubbed. > > I am running Rails 3 beta 4 with RSpec and rspec-rails beta 13 (tried pointing Gemfile to the GIT repository and did a 'bundle install', but it still installed beta 13 instead of 15 for some reason). I just pushed what I believe to be a fix for this - please try pointing Gemfile to the git repos again. It should work if you do this with all of them: gem "rspec-rails", :git => "git://github.com/rspec/rspec-rails.git" gem "rspec", :git => "git://github.com/rspec/rspec.git" gem "rspec-core", :git => "git://github.com/rspec/rspec-core.git" gem "rspec-expectations", :git => "git://github.com/rspec/rspec-expectations.git" gem "rspec-mocks", :git => "git://github.com/rspec/rspec-mocks.git" Let me know if it works out. Thx, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From dark.red.and.yellow at googlemail.com Mon Jul 5 18:16:55 2010 From: dark.red.and.yellow at googlemail.com (=?ISO-8859-1?Q?Timo_R=F6=DFner?=) Date: Mon, 5 Jul 2010 15:16:55 -0700 (PDT) Subject: [rspec-users] rspec 2 not cleaning up after examples run? In-Reply-To: <5A93ED31-40AA-4991-B7A4-E95357179B86@gmail.com> References: <6951BE91-9D73-4166-A0E4-7696E4AFF343@gmail.com> <522ebcc2-1d53-4e80-8302-67b224aa9bdb@k39g2000yqd.googlegroups.com> <2f27edf8-a9d4-4151-ad71-3e2500d99936@j4g2000yqh.googlegroups.com> <5A93ED31-40AA-4991-B7A4-E95357179B86@gmail.com> Message-ID: <98b2ee78-a326-4f6a-b9d2-651818b858d2@u26g2000yqu.googlegroups.com> Hey David, sorry for the late reply, you nailed it, that was the problem indeed..:-) Thanks a lot for the assist. Cheers On Jul 1, 2:15?pm, David Chelimsky wrote: > On Jul 1, 2010, at 3:22 AM, Timo R??ner wrote: > > > > > On Jun 30, 7:44 pm, Amiruddin Nagri wrote: > >> I am not sure if this will help or not but I was also getting data not > >> cleared properly when run specs through rake but when ran using script/spec > >> it was cleaning up the data > > >> Amir > > >> On Jun 30, 2010 10:56 PM, "David Chelimsky" wrote: > > >> On Jun 30, 2010, at 11:55 AM, Timo R??ner wrote: > > >>> On Jun 29, 12:14 pm, David Chelimsky > >> The command is rspec in rspec 2. Try: > > >> bundle exec rspec spec/models/challenge_spec.rb > > @David, > > > alright, I tried: > > > ?bundle exec rspec spec/models/challenge_spec.rb > > > -> Same results, same log output as above. > > > @Amiruddin > > > script/spec would be rails 2 / rspec 1 - my problem occurs with rails > > 3 / rspec 2 (and script/spec doesn't exist because of that). > > Hard to break the top posting habit :) I moved your comments to the bottom. > > @Timo - I'm sorry I missed this the first time through, but it's because the spec_helper config is missing this line: > > ? config.use_transactional_fixtures = true > > The post-install hook when you install rspec-rails instructs you to re-run 'script/rails generate rspec:install', and if you do so you'll see this line in the generated spec_helper. > > Let me know if that solves it. I'm pretty sure it will. > > Cheers, > David > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From lists at ruby-forum.com Tue Jul 6 06:54:24 2010 From: lists at ruby-forum.com (Jarl Friis) Date: Tue, 6 Jul 2010 12:54:24 +0200 Subject: [rspec-users] Testing render :update In-Reply-To: <85837618-776B-439A-8E19-9F64D37A3E25@gmail.com> References: <1EF979D1-2464-43BA-8E39-2CC56E512A0D@gmail.com> <85837618-776B-439A-8E19-9F64D37A3E25@gmail.com> Message-ID: <4ec9833d2e593d80df658159cca1c0a6@ruby-forum.com> David Chelimsky wrote: > > Looks like action_pack calls render twice (the 2nd time in > action_controller/metal/implicit_render.rb:10:in `default_render'), so > we've got to stub the :render call twice: > > page = double('page') > controller.stub(:render) > controller.stub(:render).with(:update).and_yield(page) > page.should_receive(:replace_html).with(...) > > Bummer. It seems like this is a rails bug (render should only get called > once, and there is code that prevents it from being called twice, but > not _all_ of the time), but I'm not sure if I can make that case or not. > I'll try :) Have this problem been reported to the rails project. I am not using rspec, but trying to stub away rendering and run into the same situation; have to call #expects twice using Mocha framework. Could it be this ticket: https://rails.lighthouseapp.com/projects/8994/tickets/2279-render-layout-with-block-and-multiple-yields -- Posted via http://www.ruby-forum.com/. From andrey.rusetskiy at gmail.com Tue Jul 6 07:49:21 2010 From: andrey.rusetskiy at gmail.com (andreyr) Date: Tue, 6 Jul 2010 04:49:21 -0700 (PDT) Subject: [rspec-users] rspec rake tasks fail inside active record Message-ID: <29084492.post@talk.nabble.com> Hi, i have a problem that any of my rspec rake tasks fail with the following error: rake -f unittests.rake spec ** Invoke spec (first_time) ** Execute spec C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext/logger.rb:53: undefined method `datetime_format=' for class `Logger' (NameError) from C:/Ruby18/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from C:/Ruby18/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext.rb:8 from C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext.rb:8:in `each' from C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext.rb:8 from C:/Ruby18/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from C:/Ruby18/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support.rb:56 ... 11 levels... from C:/Ruby18/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:14:in `load_file s' from C:/Ruby18/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/runner/options.rb:133:in `run_examples' from C:/Ruby18/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/runner/command_line.rb:9:in `run' from C:/Ruby18/lib/ruby/gems/1.8/gems/rspec-1.3.0/bin/spec:5 rake aborted! My rake tasks are trivial like this: Spec::Rake::SpecTask.new do |t| t.spec_files = FileList['lib/deposit_handler/spec/*.rb'] end I am watir+rspec. Could the problem be that activesupport being a part of rails is missing some dependencies? Googling around did not seem to bring any results. -- View this message in context: http://old.nabble.com/rspec-rake-tasks-fail-inside-active-record-tp29084492p29084492.html Sent from the rspec-users mailing list archive at Nabble.com. From dchelimsky at gmail.com Tue Jul 6 09:02:33 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 6 Jul 2010 08:02:33 -0500 Subject: [rspec-users] rspec rake tasks fail inside active record In-Reply-To: <29084492.post@talk.nabble.com> References: <29084492.post@talk.nabble.com> Message-ID: <8EF543F0-9F44-4CAD-9D18-A7CAE41F2C6B@gmail.com> On Jul 6, 2010, at 6:49 AM, andreyr wrote: > Hi, > > i have a problem that any of my rspec rake tasks fail with the following > error: > rake -f unittests.rake spec > ** Invoke spec (first_time) > ** Execute spec > C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext/logger.rb:53: > undefined method `datetime_format=' for class `Logger' (NameError) > from > C:/Ruby18/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `gem_original_require' > from > C:/Ruby18/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' > from > C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext.rb:8 > from > C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext.rb:8:in > `each' > from > C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext.rb:8 > from > C:/Ruby18/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `gem_original_require' > from > C:/Ruby18/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' > from > C:/Ruby18/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support.rb:56 > ... 11 levels... > from > C:/Ruby18/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/runner/example_group_runner.rb:14:in > `load_file > s' > from > C:/Ruby18/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/runner/options.rb:133:in > `run_examples' > from > C:/Ruby18/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/runner/command_line.rb:9:in > `run' > from C:/Ruby18/lib/ruby/gems/1.8/gems/rspec-1.3.0/bin/spec:5 > rake aborted! > > My rake tasks are trivial like this: > Spec::Rake::SpecTask.new do |t| > t.spec_files = FileList['lib/deposit_handler/spec/*.rb'] > end > > I am watir+rspec. Could the problem be that activesupport being a part of > rails is missing some dependencies? Googling around did not seem to bring > any results. We need to see some code. Please post the Rakefile and spec file. From dchelimsky at gmail.com Tue Jul 6 09:14:13 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 6 Jul 2010 08:14:13 -0500 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: Message-ID: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> On Jul 5, 2010, at 2:59 PM, Lalish-Menagh, Trevor wrote: > OK, I will chime in here, since I think I might have opened up this > can of worms. :) > > I agree with David that we should stick with wrapping the Rails public > APIs. That is: assert_generates, assert_recognizes, and assert_routing > (http://edgeapi.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html). > > OK, here is my thoughts on a format: > http://gist.github.com/464636 > > I want it to be readable in English, so let's try: > describe "routing" do > specify "days#index" do > route get('/days').should generate 'days#index' # wraps assert_generates > end > end > > specify [that the] route [path] get('/days') should generate [the > options] 'days#index' > > OK! Next: > describe "routing" do > specify "days#index" do > routing 'days#index'.should recognize get('/days') # wraps assert_recognizes > end > end > > specify [that the] route [options] 'days#index' should recognize [the > path] get('/days') > > (Might need some work... but it is uniform). Next: > describe "routing" do > specify "days#index" do > route get('/days').should be 'days#index' # wraps assert_routing > end > end > > specify [that the] route [path] get('/days') should be [the options] > 'days#index' > > Finally, this makes nested routes (my original issue) look nice: > describe "routing" do > specify "days#index" do > route 'days#index'.should recognize get('/students/1/days') with > :student_id => '1' > end > end > > specify [that the] route [options] 'days#index' should recognize [the > path] get('/students/1/days') with [extras] :student_id => '1' > > You could also write out the options longhand to include the extras, > but I think this is too ugly: > describe "routing" do > specify "days#index" do > route {:controller => 'days', :action => 'index', :student_id => > '1'}.should recognize ('/students/1/days') > end > end > > specify [that the] route [options] {:controller => 'days', :action => > 'index', :student_id => '1'} should recognize [the path] > ('/students/1/days') > > What do you think? > > Trevor Hey Trevor, These are all great DSL ideas, but they strike me as being sufficiently different from anything else in either RSpec or Rails that it would be for confusing for users. Do you have any thoughts on the other proposals? Cheers, David From akleak at gmail.com Tue Jul 6 12:00:56 2010 From: akleak at gmail.com (Arco) Date: Tue, 6 Jul 2010 09:00:56 -0700 (PDT) Subject: [rspec-users] Rspec2 Beta Changelog ? Message-ID: Is there a change log for the Rspec2 beta? I couldn't find one in the source or wiki... From dchelimsky at gmail.com Tue Jul 6 12:05:28 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 6 Jul 2010 11:05:28 -0500 Subject: [rspec-users] Rspec2 Beta Changelog ? In-Reply-To: References: Message-ID: On Jul 6, 2010, at 11:00 AM, Arco wrote: > Is there a change log for the Rspec2 beta? Just the commit logs. > > I couldn't find one in the source or wiki... From trev at trevreport.org Tue Jul 6 19:16:00 2010 From: trev at trevreport.org (Lalish-Menagh, Trevor) Date: Tue, 6 Jul 2010 19:16:00 -0400 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> References: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> Message-ID: Hi David, You make a good point. I was talking with a coworker about this problem, and he suggested a simpler format, that I think will coincide some with Wincent's thoughts. Here is my next stab (http://gist.github.com/466064): describe "routing" do it "recognizes and generates #index" do get("/days").should have_routing('days#index') end it "generates #index" do get("/days").should generate('days#index') end it "recognizes #index" do ('days#index').should recognize get("/days") end describe "nested in students" do it "recognizes #index" do ('days#index').with(:student_id => "1").should recognize get("/students/1/days") end end end Notes: - I am using have_routing, recognize, and generate because those are the verbs used in Rails for the functions we are wrapping. - I like using the word "with" to represent "extras," in the Rails API (see http://edgeapi.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html), since I think it fits here, and we already use with in RSpec in other places (like stubs, etc.). - I like using get('path') since it is similar to the routing calls in the Rails 3 route file, and I think it is easy to intuit. - We can use the hash notation to conform to Rails 3, with an option to provide a full hash as well (Rails 2 style). - The format still reads like English, and using "have_routing" instead of "routes_to" avoids the "_to" and "_from" problem that we have been talking about, PLUS it makes it easier to draw a relationship between the RSpec command and the Test::Unit command (assert_routing). - Using these verbs still allow "should_not" to make sense. Thoughts, Trevor On Tue, Jul 6, 2010 at 9:14 AM, David Chelimsky wrote: > Hey Trevor, > > These are all great DSL ideas, but they strike me as being sufficiently different from anything else in either RSpec or Rails that it would be for confusing for users. > > Do you have any thoughts on the other proposals? > > Cheers, > David -- Trevor Lalish-Menagh 484.868.6150 mobile trev at trevreport.org http://www.trevmex.com/ From trev at trevreport.org Tue Jul 6 21:54:01 2010 From: trev at trevreport.org (Lalish-Menagh, Trevor) Date: Tue, 6 Jul 2010 21:54:01 -0400 Subject: [rspec-users] Setting up rspec-rails for hacking Message-ID: I am sure most of you could do this easily, but I wanted to write down how I got there in any case, so here are my instructions on how to set up rspec-rails to hack on: http://trevmex.com/post/779078048/how-to-start-hacking-a-ruby-project Enjoy, Trevor -- Trevor Lalish-Menagh 484.868.6150 mobile trev at trevreport.org http://www.trevmex.com/ From win at wincent.com Wed Jul 7 02:24:09 2010 From: win at wincent.com (Wincent Colaiuta) Date: Wed, 7 Jul 2010 08:24:09 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> Message-ID: <9E8FA04F-8027-424B-BBC8-60AC667B79FC@wincent.com> El 07/07/2010, a las 01:16, Lalish-Menagh, Trevor escribi?: > Hi David, > > You make a good point. I was talking with a coworker about this > problem, and he suggested a simpler format, that I think will coincide > some with Wincent's thoughts. Here is my next stab > (http://gist.github.com/466064): > describe "routing" do > it "recognizes and generates #index" do > get("/days").should have_routing('days#index') > end Very nice. I definitely like this better than the "map()" terminology that I used. > it "generates #index" do > get("/days").should generate('days#index') > end Reads well, _but_ I think you've got it back-to-front. assert_generates, and therefore the corresponding matcher in RSpec, asserts that a _path_ can be generated from a set of _params_ (controller, action, additional params), but here you're asserting the opposite. (One thing to note is that assert_generates really only does assert about the _path_, not the method + path, but it's still nice to write it as "get(path)" just for symmetry with the reverse version of the spec.) > it "recognizes #index" do > ('days#index').should recognize get("/days") > end This one is back-to-front too; assert_recognizes is an assertion that a path (this time method + path) is recognized as a particular route (action, controller, additional params) but here you're asserting the opposite. If we're really serious about using the same verbs as the Rails assertions, and we want to forward and reverse versions of the spec to read in the same way, we could use something like: specify { get('/days').should recognize_as('days#index') } specify { get('/days').should generate_from('days#index') } If we don't mind swapping the order around specify { get('/days').should recognize_as('days#index') } specify { 'days#index'.should generate('/days') } Note that in the "generate" spec here I drop the "get()" seeing as Rails isn't actually looking at the method, and it is just verbiage IMO to start nesting other method calls inside the generate() matcher. Weighing up the two orders, I prefer the first pair of specs, I think, because: - the repetition of the pattern makes it easier to remember and apply. - if you have to supply additional parameters (as you do in your later example), using the first format you can write ('days#index', :student_id => '1') whereas with the second format you are obliged to involve another method like with() in order to express it as "('days#index').with(:student_id => '1')". > describe "nested in students" do > it "recognizes #index" do > ('days#index').with(:student_id => "1").should recognize > get("/students/1/days") > end > end > end This is another back-to-front one, I think. You're not recognizing here, but generating. > Notes: > - I am using have_routing, recognize, and generate because those are > the verbs used in Rails for the functions we are wrapping. Seems like a good idea that we should definitely try to do, although with one reservation; if we feel that the language is confusing or suboptimal then we should feel free to change it. I personally have lingering doubts about the Rails language because I think it _is_ confusing in a way. Look at the way you used recognize and generate back-to-front in this message. And I know that every time I want to make a comment about "assert_recognizes" and "assert_generates" I end up double-checking the API docs just to make sure that I'm about to use them in the right way. > - I like using the word "with" to represent "extras," in the Rails API > (see http://edgeapi.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html), > since I think it fits here, and we already use with in RSpec in other > places (like stubs, etc.). I don't really like it; I think it adds unnecessary verbiage to the specs. > - I like using get('path') since it is similar to the routing calls in > the Rails 3 route file, and I think it is easy to intuit. > - We can use the hash notation to conform to Rails 3, with an option > to provide a full hash as well (Rails 2 style). Yes, the example I posted at http://gist.github.com/464081 does that. > - The format still reads like English, and using "have_routing" > instead of "routes_to" avoids the "_to" and "_from" problem that we > have been talking about, PLUS it makes it easier to draw a > relationship between the RSpec command and the Test::Unit command > (assert_routing). Yeah, I think "have_routing" is a definite improvement over "map". I am less convinced that "recognize_as" is an improvement over the highly readable "map_to". I am less attached to "map_from", though, and think "generate_from" might be an improvement. Like I said above, I think the Rails terminology does have the potential to be confusing, so I don't necessarily feel "wedded" to it. > - Using these verbs still allow "should_not" to make sense. Yes, I think that's important. One thing I wanted to add is that I discovered in my testing that the existing "be_routable" matcher isn't very useful. This is because it relies on "recognize_path", which I am not sure is public API or not, and "recognize_path" sometimes recognizes the unrecognizable... For example: in config/routes.rb: resource :issues, :except => :index visit issues#index (/issues) in your browser: get a RoutingError (expected) in your spec: recognize_path('/issues', :method => :get) # recognizes! So this means you can't do stuff like get('issues#index').should_not be_routable, because the Rails recognize_path() method will tell you that it _is_ routable. Seems that it is only useful for a subset of unroutable routes (like completely non-existent resources, for example). If you look in the Gist you'll see that I work around this limitation by adding a "be_recognized" matcher which doesn't use "recognize_path()" under the hood. Instead it uses "assert_recognizes" and decides what to do based on what kind of exception, if any, gets thrown by it. So you can write: specify { get('/issues').should_not be_recognized } (Funnily enough, assert_recognizes() _does_ use recognize_path() under the hood, but it's evidently doing some additional set-up and tear-down to make it work. It seems like wrapping assert_recognizes rather than replicating its logic, though, is the right thing to do.) Cheers, Wincent From win at wincent.com Wed Jul 7 02:29:27 2010 From: win at wincent.com (Wincent Colaiuta) Date: Wed, 7 Jul 2010 08:29:27 +0200 Subject: [rspec-users] Setting up rspec-rails for hacking In-Reply-To: References: Message-ID: El 07/07/2010, a las 03:54, Lalish-Menagh, Trevor escribi?: > I am sure most of you could do this easily, but I wanted to write down > how I got there in any case, so here are my instructions on how to set > up rspec-rails to hack on: > http://trevmex.com/post/779078048/how-to-start-hacking-a-ruby-project Did you know about the rspec-dev meta project? http://github.com/rspec/rspec-dev This is a project which sets up everything you need to do RSpec development, including hacking on rspec-rails. As long as you have rake and Bundler (>= 1.0.0.beta) it is quite easy to set-up: git clone git://github.com/rspec/rspec-dev.git cd rspec-dev rake setup # clones all the rspec-* repos under "repos/" rake # runs all specs and features from rspec-* repos Perhaps we should update the rspec-* READMEs with a point back to rspec-dev so that people know about it? Cheers, Wincent From trev at trevreport.org Wed Jul 7 06:26:10 2010 From: trev at trevreport.org (Trevor Lalish-Menagh) Date: Wed, 7 Jul 2010 06:26:10 -0400 Subject: [rspec-users] Setting up rspec-rails for hacking In-Reply-To: References: Message-ID: > Did you know about the rspec-dev meta project? > > http://github.com/rspec/rspec-dev That is great. I should have looked for that before setting this up. I just didn't think about it. > Perhaps we should update the rspec-* READMEs with a point back to rspec-dev so that people know about it? Good call. That would help. Thanks, Trevor From dchelimsky at gmail.com Wed Jul 7 06:34:11 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 7 Jul 2010 05:34:11 -0500 Subject: [rspec-users] Setting up rspec-rails for hacking In-Reply-To: References: Message-ID: On Jul 7, 2010, at 5:26 AM, Trevor Lalish-Menagh wrote: >> Did you know about the rspec-dev meta project? >> >> http://github.com/rspec/rspec-dev > > That is great. I should have looked for that before setting this up. I just didn't think about it. > >> Perhaps we should update the rspec-* READMEs with a point back to rspec-dev so that people know about it? > > Good call. That would help. Done: http://github.com/rspec/rspec http://github.com/rspec/rspec-core http://github.com/rspec/rspec-expectations http://github.com/rspec/rspec-mocks http://github.com/rspec/rspec-rails Cheers, David From dchelimsky at gmail.com Wed Jul 7 07:29:55 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 7 Jul 2010 06:29:55 -0500 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <9E8FA04F-8027-424B-BBC8-60AC667B79FC@wincent.com> References: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> <9E8FA04F-8027-424B-BBC8-60AC667B79FC@wincent.com> Message-ID: On Jul 7, 2010, at 1:24 AM, Wincent Colaiuta wrote: > El 07/07/2010, a las 01:16, Lalish-Menagh, Trevor escribi?: > >> Hi David, >> >> You make a good point. I was talking with a coworker about this >> problem, and he suggested a simpler format, that I think will coincide >> some with Wincent's thoughts. Here is my next stab >> (http://gist.github.com/466064): >> describe "routing" do >> it "recognizes and generates #index" do >> get("/days").should have_routing('days#index') >> end > > Very nice. I definitely like this better than the "map()" terminology that I used. > >> it "generates #index" do >> get("/days").should generate('days#index') >> end > > Reads well, _but_ I think you've got it back-to-front. assert_generates, and therefore the corresponding matcher in RSpec, asserts that a _path_ can be generated from a set of _params_ (controller, action, additional params), but here you're asserting the opposite. > > (One thing to note is that assert_generates really only does assert about the _path_, not the method + path, but it's still nice to write it as "get(path)" just for symmetry with the reverse version of the spec.) > >> it "recognizes #index" do >> ('days#index').should recognize get("/days") >> end > > This one is back-to-front too; assert_recognizes is an assertion that a path (this time method + path) is recognized as a particular route (action, controller, additional params) but here you're asserting the opposite. > > If we're really serious about using the same verbs as the Rails assertions, and we want to forward and reverse versions of the spec to read in the same way, we could use something like: > > specify { get('/days').should recognize_as('days#index') } > specify { get('/days').should generate_from('days#index') } > > If we don't mind swapping the order around > > specify { get('/days').should recognize_as('days#index') } > specify { 'days#index'.should generate('/days') } > > Note that in the "generate" spec here I drop the "get()" seeing as Rails isn't actually looking at the method, and it is just verbiage IMO to start nesting other method calls inside the generate() matcher. > > Weighing up the two orders, I prefer the first pair of specs, I think, because: > > - the repetition of the pattern makes it easier to remember and apply. > > - if you have to supply additional parameters (as you do in your later example), using the first format you can write ('days#index', :student_id => '1') whereas with the second format you are obliged to involve another method like with() in order to express it as "('days#index').with(:student_id => '1')". > >> describe "nested in students" do >> it "recognizes #index" do >> ('days#index').with(:student_id => "1").should recognize >> get("/students/1/days") >> end >> end >> end > > This is another back-to-front one, I think. You're not recognizing here, but generating. > >> Notes: >> - I am using have_routing, recognize, and generate because those are >> the verbs used in Rails for the functions we are wrapping. > > Seems like a good idea that we should definitely try to do, although with one reservation; if we feel that the language is confusing or suboptimal then we should feel free to change it. > > I personally have lingering doubts about the Rails language because I think it _is_ confusing in a way. Look at the way you used recognize and generate back-to-front in this message. And I know that every time I want to make a comment about "assert_recognizes" and "assert_generates" I end up double-checking the API docs just to make sure that I'm about to use them in the right way. > >> - I like using the word "with" to represent "extras," in the Rails API >> (see http://edgeapi.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html), >> since I think it fits here, and we already use with in RSpec in other >> places (like stubs, etc.). > > I don't really like it; I think it adds unnecessary verbiage to the specs. > >> - I like using get('path') since it is similar to the routing calls in >> the Rails 3 route file, and I think it is easy to intuit. >> - We can use the hash notation to conform to Rails 3, with an option >> to provide a full hash as well (Rails 2 style). > > Yes, the example I posted at http://gist.github.com/464081 does that. > >> - The format still reads like English, and using "have_routing" >> instead of "routes_to" avoids the "_to" and "_from" problem that we >> have been talking about, PLUS it makes it easier to draw a >> relationship between the RSpec command and the Test::Unit command >> (assert_routing). > > Yeah, I think "have_routing" is a definite improvement over "map". > > I am less convinced that "recognize_as" is an improvement over the highly readable "map_to". > > I am less attached to "map_from", though, and think "generate_from" might be an improvement. > > Like I said above, I think the Rails terminology does have the potential to be confusing, so I don't necessarily feel "wedded" to it. > >> - Using these verbs still allow "should_not" to make sense. > > Yes, I think that's important. > > One thing I wanted to add is that I discovered in my testing that the existing "be_routable" matcher isn't very useful. This is because it relies on "recognize_path", which I am not sure is public API or not, and "recognize_path" sometimes recognizes the unrecognizable... For example: > > in config/routes.rb: > resource :issues, :except => :index > > visit issues#index (/issues) in your browser: > get a RoutingError (expected) > > in your spec: > recognize_path('/issues', :method => :get) # recognizes! > > So this means you can't do stuff like get('issues#index').should_not be_routable, because the Rails recognize_path() method will tell you that it _is_ routable. Seems that it is only useful for a subset of unroutable routes (like completely non-existent resources, for example). > > If you look in the Gist you'll see that I work around this limitation by adding a "be_recognized" matcher which doesn't use "recognize_path()" under the hood. Instead it uses "assert_recognizes" and decides what to do based on what kind of exception, if any, gets thrown by it. So you can write: > > specify { get('/issues').should_not be_recognized } > > (Funnily enough, assert_recognizes() _does_ use recognize_path() under the hood, but it's evidently doing some additional set-up and tear-down to make it work. It seems like wrapping assert_recognizes rather than replicating its logic, though, is the right thing to do.) Seems as though this format has been abandoned in this conversation: it { should route(get "/issues/new").to("issues#new") } it { should generate("/issues/new").from("issues#new") } I think that verbiage is concise and intention revealing, and keeps the path on the left and the details on the right. Supported variants would be: it { should route(:get => "/issues/new") ... # explicit hash for method/path it { should route("/issues/new")... # defaults to get it { should ...to(:controller => "issues", :action => "new") } # explicit hash for params The negative version would be: it { should_not route(get "/issues/new") } We could alias route() with recognize() to get: it { should_not recognize(get "/issues/new") } We still need to consider output. For example: it { should route("/issues/37").to("issues#show", :id => 37) } I think in this case we _might_ be able to figure out that 37 is the value of :id and output should route "/issues/:id" to "issues#show" Not sure if that'd be asking for trouble, but it seems feasible/reasonable. In terms of the more verbose format for custom messages, we could add a router() method for sugar: it "routes /issues/new to issues#new" do router.should route("/issues/new").to("issues#new") } end And we still need the bi-directional version. I'm really at a loss on this one. Thoughts? David From johnnybutler7 at gmail.com Wed Jul 7 08:31:07 2010 From: johnnybutler7 at gmail.com (johnnybutler7) Date: Wed, 7 Jul 2010 05:31:07 -0700 (PDT) Subject: [rspec-users] Remarkable Rails validations not working Message-ID: <5d959cc5-6800-4b58-82c4-76ab36f6c3d7@a30g2000yqn.googlegroups.com> Hi, Ive installed the remarkable_rails plugin(3.1.13) so i can use the macros to test the model associations and validations. For my model user i have: validates_presence_of :title, :message => 'cannot be blank!' validates_length_of :title, :within => 2..40, :too_short => 'is too short!', :too_long => 'is too long!' For my user_spec file i have: describe "validations" do subject { Factory.build(:user) } it { should_validate_presence_of :title } it { should validate_length_of(:title, :within => 2..40) } end But when i run my specs i get errors: 1) 'validations should require title to be set' FAILED Expected User to require title to be set 2) 'validations should ensure length of title is within 2..40 characters' FAILED Expected User to be invalid when title length is less than 2 characters I cant understand why this isnt working? If i write regualr rspec code it works, see below but i dont want to have to do this for every validation. it "should be invalid without a title" do @user.title = nil @user.should_not be_valid @user.errors.on(:title).size.should == 2 @user.errors.on(:title).should include("cannot be blank!") @user.errors.on(:title).should include("is too short!") end Has anyone got any ideas why the remarkable rails plugin is not validating correctly? JB From apremdas at gmail.com Wed Jul 7 09:22:38 2010 From: apremdas at gmail.com (Andrew Premdas) Date: Wed, 7 Jul 2010 14:22:38 +0100 Subject: [rspec-users] RSpec uses at_exit - forks and stuff Message-ID: Hi there. My understanding (which is limited) is that rspec uses at_exit to run its specs. I don't really know why - could somoene explain? My problem with this behaviour is that I would like the running of a spec to start an instance of solr (using Sunspot) if one is not running. The problem with this is that Sunspot forks to start solr, and when these forks exit they run my specs. At best this causes specs to be run more than once, at worst it causes specs to fail in their hundreds. I can fix this by adding an at_exit for each fork ... fork do ... at_exit { exit! } end but this means changing the Sunspot code, which I really shouldn't have to do to run specs. So is their anything else I can do. Ideally in spec_helper or another rspec support file. TIA Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: From win at wincent.com Wed Jul 7 08:39:05 2010 From: win at wincent.com (Wincent Colaiuta) Date: Wed, 7 Jul 2010 14:39:05 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> <9E8FA04F-8027-424B-BBC8-60AC667B79FC@wincent.com> Message-ID: <75BD8DC7-90E0-403F-9E6E-F64BD0D4BEAD@wincent.com> El 07/07/2010, a las 13:29, David Chelimsky escribi?: > Seems as though this format has been abandoned in this conversation: > > it { should route(get "/issues/new").to("issues#new") } > it { should generate("/issues/new").from("issues#new") } > > I think that verbiage is concise and intention revealing, and keeps the path on the left and the details on the right. True, but it also looks like it might be a little painful to implement. Seeing as you propose a little further down that we should also be able to do stuff like: it { should_not route(get "/issues/new") } That means that "route" needs to be (or return) a matcher that also, optionally, responds to the "to" message and returns another matcher. And "generate" needs to return a proxy that responds to "from" and returns the real matcher, but itself raises an exception if the user mistakenly uses it without chaining the "from" onto it. Seems fairly magical compared to what we have right now, or what I proposed earlier on. > Supported variants would be: > > it { should route(:get => "/issues/new") ... # explicit hash for method/path > it { should route("/issues/new")... # defaults to get > it { should ...to(:controller => "issues", :action => "new") } # explicit hash for params > > The negative version would be: > > it { should_not route(get "/issues/new") } > > We could alias route() with recognize() to get: > > it { should_not recognize(get "/issues/new") } Sounds sensible. > We still need to consider output. For example: > > it { should route("/issues/37").to("issues#show", :id => 37) } > > I think in this case we _might_ be able to figure out that 37 is the value of :id and output > > should route "/issues/:id" to "issues#show" > > Not sure if that'd be asking for trouble, but it seems feasible/reasonable. I don't think it's worth it, to be honest. It would add a lot of complexity just to save some characters in the spec output. (Saving characters when _writing_ the specs seems more important.) And I think it's throwing away information, because the user reading the spec now has to mentally unpack the ":id" parameter, but doesn't actually see it. Multiple examples with different :ids in them are now all going to look the same. And what if the user has complex routes with requirements and regexp formats and stuff on them? Won't that be a little hard to handle? > In terms of the more verbose format for custom messages, we could add a router() method for sugar: > > it "routes /issues/new to issues#new" do > router.should route("/issues/new").to("issues#new") } > end Yeah, adding router() is a good idea. > And we still need the bi-directional version. I'm really at a loss on this one. Perhaps something with/like the "have_routing" that Trevor suggested earlier? Possibly: it { should have_routing('/issues/new').for('issues#new') } I've pasted a comparison of the two proposals in their current forms here so we can get a side-by-side (well, above/below) look at them: http://gist.github.com/466624 Still not convinced about the bi-directional language, though (used "have_routing" in both flavors). If anyone can come up with better language I'll update the comparison. For my taste, the first one reads nicer for most of the specs, but I like the "router.should_not recognize('foo')" syntax, at least for the GET case. I like it less for the non-GET case, though, where we have to nest another method call (ie. "router.should_not recognize(put '/issues/123')". Cheers, Wincent From dchelimsky at gmail.com Wed Jul 7 10:42:55 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 7 Jul 2010 09:42:55 -0500 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <75BD8DC7-90E0-403F-9E6E-F64BD0D4BEAD@wincent.com> References: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> <9E8FA04F-8027-424B-BBC8-60AC667B79FC@wincent.com> <75BD8DC7-90E0-403F-9E6E-F64BD0D4BEAD@wincent.com> Message-ID: On Jul 7, 2010, at 7:39 AM, Wincent Colaiuta wrote: > El 07/07/2010, a las 13:29, David Chelimsky escribi?: > >> Seems as though this format has been abandoned in this conversation: >> >> it { should route(get "/issues/new").to("issues#new") } >> it { should generate("/issues/new").from("issues#new") } >> >> I think that verbiage is concise and intention revealing, and keeps the path on the left and the details on the right. > > True, but it also looks like it might be a little painful to implement. Seeing as you propose a little further down that we should also be able to do stuff like: > > it { should_not route(get "/issues/new") } > > That means that "route" needs to be (or return) a matcher that also, optionally, responds to the "to" message and returns another matcher. > > And "generate" needs to return a proxy that responds to "from" and returns the real matcher, but itself raises an exception if the user mistakenly uses it without chaining the "from" onto it. > > Seems fairly magical compared to what we have right now, or what I proposed earlier on. The chain method in matchers is intended just for this purpose: matcher :foo do |expected_foo| match do |actual| if @expected_bar # do one thing else # do another end end chain :bar do |expected_bar| @expected_bar = expected_bar end end thing.should foo('blah').bar('blah again') >> Supported variants would be: >> >> it { should route(:get => "/issues/new") ... # explicit hash for method/path >> it { should route("/issues/new")... # defaults to get >> it { should ...to(:controller => "issues", :action => "new") } # explicit hash for params >> >> The negative version would be: >> >> it { should_not route(get "/issues/new") } >> >> We could alias route() with recognize() to get: >> >> it { should_not recognize(get "/issues/new") } > > Sounds sensible. > >> We still need to consider output. For example: >> >> it { should route("/issues/37").to("issues#show", :id => 37) } >> >> I think in this case we _might_ be able to figure out that 37 is the value of :id and output >> >> should route "/issues/:id" to "issues#show" >> >> Not sure if that'd be asking for trouble, but it seems feasible/reasonable. > > I don't think it's worth it, to be honest. It would add a lot of complexity just to save some characters in the spec output. (Saving characters when _writing_ the specs seems more important.) And I think it's throwing away information, because the user reading the spec now has to mentally unpack the ":id" parameter, but doesn't actually see it. Multiple examples with different :ids in them are now all going to look the same. And what if the user has complex routes with requirements and regexp formats and stuff on them? Won't that be a little hard to handle? Agreed. I was thinking of an earlier suggestion that the output should read in a more generic way, but that can be managed explicitly by the spec-author. >> In terms of the more verbose format for custom messages, we could add a router() method for sugar: >> >> it "routes /issues/new to issues#new" do >> router.should route("/issues/new").to("issues#new") } >> end > > Yeah, adding router() is a good idea. > >> And we still need the bi-directional version. I'm really at a loss on this one. > > Perhaps something with/like the "have_routing" that Trevor suggested earlier? Possibly: > > it { should have_routing('/issues/new').for('issues#new') } > > I've pasted a comparison of the two proposals in their current forms here so we can get a side-by-side (well, above/below) look at them: > > http://gist.github.com/466624 > > Still not convinced about the bi-directional language, though (used "have_routing" in both flavors). If anyone can come up with better language I'll update the comparison. How about going back to map, with to_and_from: it { should map(get "/issues/new").to_and_from("issues#new") } ????? > > For my taste, the first one reads nicer for most of the specs, but I like the "router.should_not recognize('foo')" syntax, at least for the GET case. I like it less for the non-GET case, though, where we have to nest another method call (ie. "router.should_not recognize(put '/issues/123')". What don't you like about the nesting? > > Cheers, > Wincent From win at wincent.com Wed Jul 7 11:00:25 2010 From: win at wincent.com (Wincent Colaiuta) Date: Wed, 7 Jul 2010 17:00:25 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> <9E8FA04F-8027-424B-BBC8-60AC667B79FC@wincent.com> <75BD8DC7-90E0-403F-9E6E-F64BD0D4BEAD@wincent.com> Message-ID: <0B3036BC-EA78-46C8-BF13-DC568A9E7864@wincent.com> El 07/07/2010, a las 16:42, David Chelimsky escribi?: > On Jul 7, 2010, at 7:39 AM, Wincent Colaiuta wrote: > >> El 07/07/2010, a las 13:29, David Chelimsky escribi?: > > How about going back to map, with to_and_from: > > it { should map(get "/issues/new").to_and_from("issues#new") } > > ????? "?????" is precisely what I think whenever I try to figure out the question of naming this particular thing... >> For my taste, the first one reads nicer for most of the specs, but I like the "router.should_not recognize('foo')" syntax, at least for the GET case. I like it less for the non-GET case, though, where we have to nest another method call (ie. "router.should_not recognize(put '/issues/123')". > > What don't you like about the nesting? Well, it's subtle, but it smells bad to me because it feels like unnecessary indirection. Instead of saying: this_thing.should satisfy(that_thing) I'm forced to say: this_thing.should satisfy(transform(that_thing)) ie. the nested method in there is transforming "that_thing" to make it suitable for consumption by the "satisfy" matcher. Seeing as we provide the "satisfy" matcher and we also define the requirements for its input, it feels somehow wrong to make the user feed the input through an additional, intermediate method. Why not just make the "satisfy" matcher accept the "that_thing" input as-is? Or any needed transformation itself? So this is why: it { should map(:get => '/issues/new').to_and_from('issues#new') } Feels "right", at least to me, compared to: it { should map(get '/issues/new').to_and_from('issues#new') } Which smells. Seeing as we provide the "map" matcher, at least in the common case of the GET request, we can apply the shortcut that you mentioned earlier and assume GET if not explicitly stated; eg. it { should map('/issues/new').to_and_from('issues#new') } Like I said, it's subtle. To me it feels ok to have an unnested transformer on the left side of the "should"; eg: specify { get('/issues/new').should route('issues#new') } But nesting it inside a matcher just sets off alarm bells for me. (Even worse than the "too much magic" alarm bells that ring for me when I see matcher chaining.) Cheers, Wincent From dchelimsky at gmail.com Wed Jul 7 20:01:48 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 7 Jul 2010 19:01:48 -0500 Subject: [rspec-users] RSpec uses at_exit - forks and stuff In-Reply-To: References: Message-ID: <128D01B3-24F7-4D16-8F7F-C77517EABE23@gmail.com> On Jul 7, 2010, at 8:22 AM, Andrew Premdas wrote: > Hi there. > > My understanding (which is limited) is that rspec uses at_exit to run its specs. I don't really know why - could somoene explain? The initial motivation was that it makes it easy to make sure it works whether you run it with the ruby command or the rspec command. Over the years it has caused some trouble though, so I'd be interested in a different solution. > My problem with this behaviour is that I would like the running of a spec to start an instance of solr (using Sunspot) if one is not running. The problem with this is that Sunspot forks to start solr, and when these forks exit they run my specs. At best this causes specs to be run more than once, at worst it causes specs to fail in their hundreds. > > I can fix this by adding an at_exit for each fork ... > > fork do > ... > at_exit { exit! } > end > > but this means changing the Sunspot code, which I really shouldn't have to do to run specs. So is their anything else I can do. Ideally in spec_helper or another rspec support file. I added RSpec::Core::Runner.disable_autorun! to beta.16 in order to solve a similar problem. No guarantees it will stay there if I come up with a better way to deal with supporting multiple entry points, but if I remove it I'll formally deprecate it (so you're safe to use it). HTH, David > > TIA > > Andrew > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From trev at trevreport.org Wed Jul 7 22:45:32 2010 From: trev at trevreport.org (Lalish-Menagh, Trevor) Date: Wed, 7 Jul 2010 22:45:32 -0400 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: <0B3036BC-EA78-46C8-BF13-DC568A9E7864@wincent.com> References: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> <9E8FA04F-8027-424B-BBC8-60AC667B79FC@wincent.com> <75BD8DC7-90E0-403F-9E6E-F64BD0D4BEAD@wincent.com> <0B3036BC-EA78-46C8-BF13-DC568A9E7864@wincent.com> Message-ID: OK, here is an idea. I was thinking about how to make routing tests that make sense. I agree with Wincent that the Rails verbiage for the routing tests is confusing, but what is NOT confusing is the new routing format, so why not try out this format (http://gist.github.com/467563): describe 'routing another way' do it { should have_resources(:days) } it { should get('/days' => 'days#index') } it { should match('/days' => 'days#index', :via => :get) } it { should recognize('/days', :via => :get).as('days#index') } it { should generate('days#index').from('/days', :via => :get) } it { should recognize('/students/1/days', :via => :get).as('days#index', :student_id => '1') } end Notes: it { should have_resources(:days) } - tests all resource routes (index, show, etc.) it { should get('/days' => 'days#index') } - wrapper for assert_routing({:method => :get, :path => '/days'}, {:controller => 'days', :action => 'index'}) it { should match('/days' => 'days#index', :via => :get) } - same as the previous example it { should recognize('/days', :via => :get).as('days#index') } - wrapper for assert_recognizes({:controller => 'days', :action => 'index'}, {:method => :get, :path => '/days'}) it { should generate('days#index').from('/days', :via => :get) } - wrapper for assert_generates({:method => :get, :path => '/days'}, {:controller => 'days', :action => 'index'}) it { should recognize('/students/1/days', :via => :get).as('days#index', :student_id => '1') } - wrapper for assert_recognizes({:controller => 'days', :action => 'index', :student_id => '1'}, {:method => :get, :path => '/students/1/days'}) The Rails test read backwards, look at this example from http://edgeapi.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html: # assert that POSTing to /items will call the create action on ItemsController assert_recognizes({:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post}) The comment reads like the inverse of the actual method call. I think that recognize(path).as(options) reads better (more like the comment above). The same goes for generate(options).from(path). This approach gives us a very Rails-readable test and keeps it readable. Thoughts? Trevor On Wed, Jul 7, 2010 at 11:00 AM, Wincent Colaiuta wrote: > El 07/07/2010, a las 16:42, David Chelimsky escribi?: > >> On Jul 7, 2010, at 7:39 AM, Wincent Colaiuta wrote: >> >>> El 07/07/2010, a las 13:29, David Chelimsky escribi?: >> >> How about going back to map, with to_and_from: >> >> ?it { should map(get "/issues/new").to_and_from("issues#new") } >> >> ????? > > "?????" is precisely what I think whenever I try to figure out the question of naming this particular thing... > >>> For my taste, the first one reads nicer for most of the specs, but I like the "router.should_not recognize('foo')" syntax, at least for the GET case. I like it less for the non-GET case, though, where we have to nest another method call (ie. "router.should_not recognize(put '/issues/123')". >> >> What don't you like about the nesting? > > Well, it's subtle, but it smells bad to me because it feels like unnecessary indirection. Instead of saying: > > ? this_thing.should satisfy(that_thing) > > I'm forced to say: > > ? this_thing.should satisfy(transform(that_thing)) > > ie. the nested method in there is transforming "that_thing" to make it suitable for consumption by the "satisfy" matcher. > > Seeing as we provide the "satisfy" matcher and we also define the requirements for its input, it feels somehow wrong to make the user feed the input through an additional, intermediate method. Why not just make the "satisfy" matcher accept the "that_thing" input as-is? Or any needed transformation itself? > > So this is why: > > ?it { should map(:get => '/issues/new').to_and_from('issues#new') } > > Feels "right", at least to me, compared to: > > ?it { should map(get '/issues/new').to_and_from('issues#new') } > > Which smells. > > Seeing as we provide the "map" matcher, at least in the common case of the GET request, we can apply the shortcut that you mentioned earlier and assume GET if not explicitly stated; eg. > > ?it { should map('/issues/new').to_and_from('issues#new') } > > Like I said, it's subtle. To me it feels ok to have an unnested transformer on the left side of the "should"; eg: > > ?specify { get('/issues/new').should route('issues#new') } > > But nesting it inside a matcher just sets off alarm bells for me. (Even worse than the "too much magic" alarm bells that ring for me when I see matcher chaining.) > > Cheers, > Wincent > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > -- Trevor Lalish-Menagh 484.868.6150 mobile trev at trevreport.org http://www.trevmex.com/ From win at wincent.com Thu Jul 8 02:25:56 2010 From: win at wincent.com (Wincent Colaiuta) Date: Thu, 8 Jul 2010 08:25:56 +0200 Subject: [rspec-users] Possible improvements to routing spec API In-Reply-To: References: <34C36264-CDA4-4767-9C21-58997B09C279@gmail.com> <9E8FA04F-8027-424B-BBC8-60AC667B79FC@wincent.com> <75BD8DC7-90E0-403F-9E6E-F64BD0D4BEAD@wincent.com> <0B3036BC-EA78-46C8-BF13-DC568A9E7864@wincent.com> Message-ID: <6B6077A7-C771-40E3-AEDE-AD2BA696F703@wincent.com> El 08/07/2010, a las 04:45, Lalish-Menagh, Trevor escribi?: > OK, here is an idea. I was thinking about how to make routing tests > that make sense. I agree with Wincent that the Rails verbiage for the > routing tests is confusing, but what is NOT confusing is the new > routing format, so why not try out this format > (http://gist.github.com/467563): > > describe 'routing another way' do > it { should have_resources(:days) } > it { should get('/days' => 'days#index') } > it { should match('/days' => 'days#index', :via => :get) } > it { should recognize('/days', :via => :get).as('days#index') } > it { should generate('days#index').from('/days', :via => :get) } > it { should recognize('/students/1/days', :via => > :get).as('days#index', :student_id => '1') } > end [snipped for brevity] > it { should generate('days#index').from('/days', :via => :get) } Hehe. You got it back-to-front again. "assert_generates" asserts that a _path_ is generated from a set of params (action, controller, additional params). Here you are doing the opposite, saying that certain params (action, controller) get generated from a path. > The Rails test read backwards, look at this example from > http://edgeapi.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html: > # assert that POSTing to /items will call the create action on ItemsController > assert_recognizes({:controller => 'items', :action => 'create'}, > {:path => 'items', :method => :post}) > > The comment reads like the inverse of the actual method call. I think > that recognize(path).as(options) reads better (more like the comment > above). I think that's the general pattern of pretty much all Test::Unit assertions which compare two parameters. Where RSpec tends to say: actual.should == expected Test::Unit tends to say: assert expected, actual > Thoughts? Well, this comes back to the eternal question of specing things like validations. Where the spec ends up being an almost identical re-statement of the implementation: validates_presence_of :foo it { should validate_presence_of(:foo) } Are you testing the Rails validation code itself (which is already tested)? Are you testing that you remembered to include the validation itself? Do you trust your "validate_presence_of" matcher? Are you testing your ability to cut and paste? etc. Well, same questions can arise with routing when the implementation and spec look like this: resource :days it { should have_resource(:days) } So, when I see this kind of thing, I think _what_ are we trying to achieve in our routing specs and _why_? At least for me, the answers are: 1. Confirm: To confirm that the routes I've defined actually do what I think they do 2. Describe: To serve as a complete, explicit, readable specification of the behavior I expect from my routes And finally: 3. That the Rails routing code actually works as advertised This last one is a bit dubious, but the truth is the Rails 3 router is a complete re-write and bugs in it and incompatibilities with the old router are being found and squished constantly. An exhaustive set of routing specs can definitely help to uncover undiscovered edge cases. So, bearing in mind those goals, what I actually need from RSpec in order to achieve them is: - most importantly, a way of asserting that a user action (eg. HTTP verb + path + params) gets routed to a given controller + action with certain additional parameters (ie. a wrapper for assert_recognizes) - less importantly, a way of asserting that a set of params (action, controller, additional params) generates a particular path (ie. a wrapper for assert_generates); this is less important for me because in practice close to all (98%) of my URL generation is done with named URL helpers, and I can test those explicitly if I want - as syntactic sugar, a way of combining the above two assertions into one for those cases where the mapping is perfectly bidirectional (ie. a wrapper for assert_routing). With these tools I can achieve pretty much everything I need: not only test that user actions end up hitting the right spots in my application, but also specify clearly and explicitly what I expect those mappings to be. So for me, anything else doesn't really help me achieve my goals. The "have_resource(s)" matcher, for instance, doesn't help me and in fact actually undermines my goal of providing a complete and explicit specification of how my routes work. The "recognize" and "generate" matchers you suggest obviously are "on target" to help me fulfill my goals. Of these, the "recognize" one is the most important one though. Of the "match" and "get" matchers you suggest, seeing as they both wrap the same thing (assert_routing), one of them would have to go. I'd probably ditch "match" because it is just a repetition of the router DSL method of the same name, and my goal here isn't just to repeat that DSL in my specs. In fact, if you look at my most important goal -- asserting that a user action (HTTP verb, path, params) hits a specific end point (controller + action + additional params) -- you'll understand why, in my proposal, all of my specifications start with "get"/"post" etc followed by path, params and then controller/action. It's not just for resonance with other parts of RSpec like where we use "get" etc in controller specs. But if the goal is just to wrap the 3 Rails assertions as faithfully as possible, then you wind up with a different proposal. What David has posted is probably the closest to this goal. And if the goal is make the specs map as closely as possible onto the language of config/routes.rb, then you wind up with a different proposal still... (ie. the one you just made). So, I guess what I'm saying here is I'd like to hear _what_ people are wanting to achieve in their routing specs and _why_; and then to ask what kind of means RSpec should provide to best achieve those goals. Cheers, Wincent From lists at ruby-forum.com Thu Jul 8 03:27:49 2010 From: lists at ruby-forum.com (Juanma Cervera) Date: Thu, 8 Jul 2010 09:27:49 +0200 Subject: [rspec-users] How to test an app with multiple databases? In-Reply-To: <4B9474A2.8030800@benmabey.com> References: <57c63afe1003070750i50f27b31l267ce6966f087ea5@mail.gmail.com> <21ea442916c5378441b867140b8c891c@ruby-forum.com> <57c63afe1003070842l2a4fcd31k3ab6276800f1bb5@mail.gmail.com> <4B9474A2.8030800@benmabey.com> Message-ID: Ben Mabey wrote: > Spec::Runner.configure do |c| > c.before(:each) do > ActiveRecord::Base::establish_connection :secondary_db > DatabaseCleaner.start > ActiveRecord::Base::establish_connection :primary_db > end > > c.after(:each) do > ActiveRecord::Base::establish_connection :secondary_db > DatabaseCleaner.clean > ActiveRecord::Base::establish_connection :primary_db > > end > end How would I translate this code for rspec 2.0.0.beta.15? I am using Rspec::Core::Runner but it has no configure method. Thanks -- Posted via http://www.ruby-forum.com/. From andrey.rusetskiy at gmail.com Thu Jul 8 04:29:38 2010 From: andrey.rusetskiy at gmail.com (andreyr) Date: Thu, 8 Jul 2010 01:29:38 -0700 (PDT) Subject: [rspec-users] rspec rake tasks fail inside active record In-Reply-To: <8EF543F0-9F44-4CAD-9D18-A7CAE41F2C6B@gmail.com> References: <29084492.post@talk.nabble.com> <8EF543F0-9F44-4CAD-9D18-A7CAE41F2C6B@gmail.com> Message-ID: <29100748.post@talk.nabble.com> Hi David, it would be difficult to do as I would need to post something like 15 files that are used in the spec file, otherwise the code would make no sense. However, I have solved the problem. While trying to make a meaningful example for you, I narrowed the problem down to the single line of code which is require 'firewatir' This is an older module not needed anymore and it was creating the problem. After dropping it things started to work. It definitely was not an rspec problem, even though it looked so from the error messages. I am still wondering why running the same spec file with the spec command worked but with rake did not. I noticed that the list of loaded modules is different when running with spec as compared to running with rake. Spec loads activesupport much earlier than rake and I think this is the answer - by the time when firewatir wants to access logger in case of using spec it's already there but in case of rake not. Anyway the problem is solved, thanks for your help. David Chelimsky-2 wrote: > > > We need to see some code. Please post the Rakefile and spec file. > > -- View this message in context: http://old.nabble.com/rspec-rake-tasks-fail-inside-active-record-tp29084492p29100748.html Sent from the rspec-users mailing list archive at Nabble.com. From apremdas at gmail.com Thu Jul 8 05:24:03 2010 From: apremdas at gmail.com (Andrew Premdas) Date: Thu, 8 Jul 2010 10:24:03 +0100 Subject: [rspec-users] RSpec uses at_exit - forks and stuff In-Reply-To: <128D01B3-24F7-4D16-8F7F-C77517EABE23@gmail.com> References: <128D01B3-24F7-4D16-8F7F-C77517EABE23@gmail.com> Message-ID: On 8 July 2010 01:01, David Chelimsky wrote: > On Jul 7, 2010, at 8:22 AM, Andrew Premdas wrote: > > > Hi there. > > > > My understanding (which is limited) is that rspec uses at_exit to run its > specs. I don't really know why - could somoene explain? > > The initial motivation was that it makes it easy to make sure it works > whether you run it with the ruby command or the rspec command. Over the > years it has caused some trouble though, so I'd be interested in a different > solution. > > > My problem with this behaviour is that I would like the running of a spec > to start an instance of solr (using Sunspot) if one is not running. The > problem with this is that Sunspot forks to start solr, and when these forks > exit they run my specs. At best this causes specs to be run more than once, > at worst it causes specs to fail in their hundreds. > > > > I can fix this by adding an at_exit for each fork ... > > > > fork do > > ... > > at_exit { exit! } > > end > > > > but this means changing the Sunspot code, which I really shouldn't have > to do to run specs. So is their anything else I can do. Ideally in > spec_helper or another rspec support file. > > I added RSpec::Core::Runner.disable_autorun! to beta.16 in order to solve a > similar problem. No guarantees it will stay there if I come up with a better > way to deal with supporting multiple entry points, but if I remove it I'll > formally deprecate it (so you're safe to use it). > > HTH, > David > > Thanks for your reply David. Does this only apply only to rspec2? (the beta 16 seems a bit of a giveaway). Is there something I can do with rspec 1x. I've tried commenting out require 'spec/autorun', but that had no effect. Is there is something I could do like put a monkey patch in spec helper. On a related note, can rspec 2 be used on rails 2x projects All best Andrew > > > TIA > > > > Andrew > > _______________________________________________ > > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From biot023 at gmail.com Thu Jul 8 05:29:15 2010 From: biot023 at gmail.com (doug livesey) Date: Thu, 8 Jul 2010 10:29:15 +0100 Subject: [rspec-users] Accessing view helpers to spec cell views, Rails3, RSpec2 Message-ID: Hi -- I'm trying to use the excellent Cells gem in a Rails 3 project with RSpec 2. I've got the 'controller' bit of the cells specced okay, but I'm struggling with the 'view' bit. What I want to do is to use RSpec's view helper methods to render the views, but don't know how to access them. I've tried declaring the spec like this: describe "tabs/show.html.haml", :type => :view do ... end This, however, still won't give me access to the assign( key, value ) method, so I guess I'm still drawing a blank, there. Could someone advise me on how to access the view helpers in a spec that falls outside of the normal rails dir structure? (The actual path to the spec in question is "spec/cells/tabs/show.html.haml_spec.rb", and the file being specced is "app/cells/tabs/show.html.haml".) Thanks for any & all help, Doug. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at ruby-forum.com Thu Jul 8 06:04:55 2010 From: lists at ruby-forum.com (Juanma Cervera) Date: Thu, 8 Jul 2010 12:04:55 +0200 Subject: [rspec-users] Testing equality Message-ID: <6948144278486ee2d0d3d76fe7d55eae@ruby-forum.com> Hello How can I test equality with two objects when they include some attribute that is BigDecimal? if I make something like this: it "should ...whatever" do obj = Factory.create(:my_object) ... MyObject.first.should == obj end. FAILS This fails because the object expected is different from the object gotten, and the only difference are the BigDecimal attributes, that are different objects, even though they have the same value. Thanks. -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Thu Jul 8 06:34:17 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 8 Jul 2010 05:34:17 -0500 Subject: [rspec-users] How to test an app with multiple databases? In-Reply-To: References: <57c63afe1003070750i50f27b31l267ce6966f087ea5@mail.gmail.com> <21ea442916c5378441b867140b8c891c@ruby-forum.com> <57c63afe1003070842l2a4fcd31k3ab6276800f1bb5@mail.gmail.com> <4B9474A2.8030800@benmabey.com> Message-ID: On Jul 8, 2010, at 2:27 AM, Juanma Cervera wrote: > Ben Mabey wrote: >> Spec::Runner.configure do |c| >> c.before(:each) do >> ActiveRecord::Base::establish_connection :secondary_db >> DatabaseCleaner.start >> ActiveRecord::Base::establish_connection :primary_db >> end >> >> c.after(:each) do >> ActiveRecord::Base::establish_connection :secondary_db >> DatabaseCleaner.clean >> ActiveRecord::Base::establish_connection :primary_db >> >> end >> end > > How would I translate this code for rspec 2.0.0.beta.15? > I am using Rspec::Core::Runner but it has no configure method. http://github.com/rspec/rspec-core/blob/master/Upgrade.markdown HTH, David From dchelimsky at gmail.com Thu Jul 8 06:46:54 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 8 Jul 2010 05:46:54 -0500 Subject: [rspec-users] RSpec uses at_exit - forks and stuff In-Reply-To: References: <128D01B3-24F7-4D16-8F7F-C77517EABE23@gmail.com> Message-ID: On Jul 8, 2010, at 4:24 AM, Andrew Premdas wrote: > On 8 July 2010 01:01, David Chelimsky wrote: > On Jul 7, 2010, at 8:22 AM, Andrew Premdas wrote: > > > Hi there. > > > > My understanding (which is limited) is that rspec uses at_exit to run its specs. I don't really know why - could somoene explain? > > The initial motivation was that it makes it easy to make sure it works whether you run it with the ruby command or the rspec command. Over the years it has caused some trouble though, so I'd be interested in a different solution. > > > My problem with this behaviour is that I would like the running of a spec to start an instance of solr (using Sunspot) if one is not running. The problem with this is that Sunspot forks to start solr, and when these forks exit they run my specs. At best this causes specs to be run more than once, at worst it causes specs to fail in their hundreds. > > > > I can fix this by adding an at_exit for each fork ... > > > > fork do > > ... > > at_exit { exit! } > > end > > > > but this means changing the Sunspot code, which I really shouldn't have to do to run specs. So is their anything else I can do. Ideally in spec_helper or another rspec support file. > > I added RSpec::Core::Runner.disable_autorun! to beta.16 in order to solve a similar problem. No guarantees it will stay there if I come up with a better way to deal with supporting multiple entry points, but if I remove it I'll formally deprecate it (so you're safe to use it). > > HTH, > David > > Thanks for your reply David. Does this only apply only to rspec2? Yes. > (the beta 16 seems a bit of a giveaway). Is there something I can do with rspec 1x. Not sure, but I really don't have time to experiment with this right now - sorry. If you do, and come up with something, please post it back and I'll look at merging it. > I've tried commenting out require 'spec/autorun', but that had no effect. Is there is something I could do like put a monkey patch in spec helper. > > On a related note, can rspec 2 be used on rails 2x projects Not quite yet. Definitely in the plan, but probably not going to happen until the fall unless someone other than me makes it so. There is http://github.com/rsanheim/rspec-rails23, which works with a subset of rspec-rails-2 functionality and only up to beta.8. This is likely NOT to be the basis for an official rspec2-rails2 gem so please don't use this expecting a smooth upgrade path once such a gem exists. HTH, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Thu Jul 8 06:58:39 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 8 Jul 2010 05:58:39 -0500 Subject: [rspec-users] Accessing view helpers to spec cell views, Rails3, RSpec2 In-Reply-To: References: Message-ID: On Jul 8, 2010, at 4:29 AM, doug livesey wrote: > Hi -- I'm trying to use the excellent Cells gem in a Rails 3 project with RSpec 2. > I've got the 'controller' bit of the cells specced okay, but I'm struggling with the 'view' bit. > What I want to do is to use RSpec's view helper methods to render the views, but don't know how to access them. > I've tried declaring the spec like this: > describe "tabs/show.html.haml", :type => :view do :type => xxx isn't directly supported yet (not sure if it will be or not), but you can use it yourself and then do this in your spec_helper: RSpec.configure do |c| c.include RSpec::Rails::ViewExampleGroup, :type => :view end HTH, David > ... > end > > This, however, still won't give me access to the assign( key, value ) method, so I guess I'm still drawing a blank, there. > Could someone advise me on how to access the view helpers in a spec that falls outside of the normal rails dir structure? > (The actual path to the spec in question is "spec/cells/tabs/show.html.haml_spec.rb", and the file being specced is "app/cells/tabs/show.html.haml".) > Thanks for any & all help, > Doug. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Thu Jul 8 07:23:47 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 8 Jul 2010 06:23:47 -0500 Subject: [rspec-users] Testing equality In-Reply-To: <6948144278486ee2d0d3d76fe7d55eae@ruby-forum.com> References: <6948144278486ee2d0d3d76fe7d55eae@ruby-forum.com> Message-ID: <6402C201-34FF-434C-86AC-92F517BCC391@gmail.com> On Jul 8, 2010, at 5:04 AM, Juanma Cervera wrote: > Hello > How can I test equality with two objects when they include some > attribute that is BigDecimal? > > if I make something like this: > > it "should ...whatever" do > obj = Factory.create(:my_object) > ... > MyObject.first.should == obj > end. > > FAILS > > This fails because the object expected is different from the object > gotten, and the only difference are the BigDecimal attributes, that are > different objects, even though they have the same value. rspec delegates ==() to the objects being compared. It's up to library providers and users to override ==() in a way that is sane in a given context. Assuming a single BigDecimal attr named amount, something like this: def ==(other) self.attributes.merge(:amount => BigDecimal.new(self.amount.to_s)) == other.attributes.merge(:amount => BigDecimal.new(other.amount.to_s)) end HTH, David From biot023 at gmail.com Thu Jul 8 08:14:31 2010 From: biot023 at gmail.com (doug livesey) Date: Thu, 8 Jul 2010 13:14:31 +0100 Subject: [rspec-users] Accessing view helpers to spec cell views, Rails3, RSpec2 In-Reply-To: References: Message-ID: Perfect, thankyou! :) On 8 July 2010 11:58, David Chelimsky wrote: > On Jul 8, 2010, at 4:29 AM, doug livesey wrote: > > Hi -- I'm trying to use the excellent Cells gem > in a Rails 3 project with RSpec 2. > I've got the 'controller' bit of the cells specced okay, but I'm struggling > with the 'view' bit. > What I want to do is to use RSpec's view helper methods to render the > views, but don't know how to access them. > I've tried declaring the spec like this: > describe "tabs/show.html.haml", :type => :view do > > > :type => xxx isn't directly supported yet (not sure if it will be or not), > but you can use it yourself and then do this in your spec_helper: > > RSpec.configure do |c| > c.include RSpec::Rails::ViewExampleGroup, :type => :view > end > > HTH, > David > > ... > end > > This, however, still won't give me access to the assign( key, value ) > method, so I guess I'm still drawing a blank, there. > Could someone advise me on how to access the view helpers in a spec that > falls outside of the normal rails dir structure? > (The actual path to the spec in question is > "spec/cells/tabs/show.html.haml_spec.rb", and the file being specced is > "app/cells/tabs/show.html.haml".) > Thanks for any & all help, > Doug. > > > _______________________________________________ > 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 apremdas at gmail.com Thu Jul 8 07:47:50 2010 From: apremdas at gmail.com (Andrew Premdas) Date: Thu, 8 Jul 2010 12:47:50 +0100 Subject: [rspec-users] RSpec uses at_exit - forks and stuff In-Reply-To: References: <128D01B3-24F7-4D16-8F7F-C77517EABE23@gmail.com> Message-ID: On 8 July 2010 11:46, David Chelimsky wrote: > On Jul 8, 2010, at 4:24 AM, Andrew Premdas wrote: > > On 8 July 2010 01:01, David Chelimsky wrote: > >> On Jul 7, 2010, at 8:22 AM, Andrew Premdas wrote: >> >> > Hi there. >> > >> > My understanding (which is limited) is that rspec uses at_exit to run >> its specs. I don't really know why - could somoene explain? >> >> The initial motivation was that it makes it easy to make sure it works >> whether you run it with the ruby command or the rspec command. Over the >> years it has caused some trouble though, so I'd be interested in a different >> solution. >> >> > My problem with this behaviour is that I would like the running of a >> spec to start an instance of solr (using Sunspot) if one is not running. The >> problem with this is that Sunspot forks to start solr, and when these forks >> exit they run my specs. At best this causes specs to be run more than once, >> at worst it causes specs to fail in their hundreds. >> > >> > I can fix this by adding an at_exit for each fork ... >> > >> > fork do >> > ... >> > at_exit { exit! } >> > end >> > >> > but this means changing the Sunspot code, which I really shouldn't have >> to do to run specs. So is their anything else I can do. Ideally in >> spec_helper or another rspec support file. >> >> I added RSpec::Core::Runner.disable_autorun! to beta.16 in order to solve >> a similar problem. No guarantees it will stay there if I come up with a >> better way to deal with supporting multiple entry points, but if I remove it >> I'll formally deprecate it (so you're safe to use it). >> >> HTH, >> David >> >> Thanks for your reply David. Does this only apply only to rspec2? > > > Yes. > > (the beta 16 seems a bit of a giveaway). Is there something I can do with > rspec 1x. > > > Not sure, but I really don't have time to experiment with this right now - > sorry. If you do, and come up with something, please post it back and I'll > look at merging it. > > I've tried commenting out require 'spec/autorun', but that had no effect. > Is there is something I could do like put a monkey patch in spec helper. > > On a related note, can rspec 2 be used on rails 2x projects > > > Not quite yet. Definitely in the plan, but probably not going to happen > until the fall unless someone other than me makes it so. > > There is http://github.com/rsanheim/rspec-rails23, which works with a > subset of rspec-rails-2 functionality and only up to beta.8. This is likely > NOT to be the basis for an official rspec2-rails2 gem so please don't use > this expecting a smooth upgrade path once such a gem exists. > > HTH, > David > > Thanks for your input David, current fix is to monkey patch the offending code and add at_exit { exit! } to the end of each fork block. Not pretty, but it will do for now. Clearly we will have to bite the bullet and go to rails3 rspec2 at some point, struggling to keep up with the pace of change at the moment. All best Andrew > > _______________________________________________ > 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 frankjmattia at gmail.com Thu Jul 8 12:17:31 2010 From: frankjmattia at gmail.com (Frank J. Mattia) Date: Thu, 8 Jul 2010 09:17:31 -0700 (PDT) Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. Message-ID: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> Looks like I didn't read the instructions before posting... I'm hoping that the "moderator" is /dev/null - otherwise this might come up as a repost. Anyway. I want my controller to set certain attributes on #create and #update (mostly created_by, updated_by... etc.) -- implementing this is easy. Testing it before implementing it has been nearly impossible for me. As a side note: I have put this logic into the controller on purpose. I do believe in the fat model/skinny controller paradigm but believe that for this situation, it's the controllers responsibility for a variety of reasons. Not the least of which being the controller has access to the session and knows who's doing what to whom. I could just put the current_user_id in a hidden field on the forms but I can't help but think that would lead to tampering... Anyway. My controller does something like this for create @object = Object.new(params[:object]) @object.created_by = current_user if @object.save... yadda yadda yadda... I have my model spec testing for the presence of created_by but I feel compelled to test that my controller is correctly setting current_user on its appropriate actions. Does this seem reasonable? If so, what's the proper way to test it? I tried testing first and though my failings ended up with an implementation first but that's neither here nor there. Any insight? Thanks, - FJM From nick.rutherford at gmail.com Thu Jul 8 12:36:00 2010 From: nick.rutherford at gmail.com (nruth) Date: Thu, 8 Jul 2010 09:36:00 -0700 (PDT) Subject: [rspec-users] rspec-rails how to selectively turn on csrf protection for controller specs? Message-ID: I'm setting up a Paypal IPN listener and need the create action to not use rails' default CSRF protection. I've got that working fine & test it actually works with cucumber (where I've turned CSRF back on, since it's full-stack testing) but would like my controller spec to mention the need for protect_from_forgery :except => [:create] (and fail when it's not set). I've not had any luck with telling the controller or ActionController::Base to use forgery protection in the spec and am a bit stuck. Has anyone done this before, or do any of these look possible: * reload the rails app for part of the spec, using a different rails initializer (i.e. without config.action_controller.allow_forgery_protection = false as in environments/test.rb) * tell the controller to use forgery protection despite it being turned off in the rails test environment config (haven't had any luck with this so far). * have some specs split off from the main specs which run in a different rails environment, e.g. test-with-csrf rather than test. versions: rails 2.3.8, rspec 1.3.0, rspec-rails 1.3.2 Any help or pointers to old topics would be greatly appreciated, google made this look a bit unexplored beyond "rails fixes csrf by default, turn off in tests". Cheers Nick From win at wincent.com Thu Jul 8 12:43:30 2010 From: win at wincent.com (Wincent Colaiuta) Date: Thu, 8 Jul 2010 18:43:30 +0200 Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> Message-ID: <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> El 08/07/2010, a las 18:17, Frank J. Mattia escribi?: > My controller does something like this for create > @object = Object.new(params[:object]) > @object.created_by = current_user > if @object.save... yadda yadda yadda... > > I have my model spec testing for the presence of created_by but I feel > compelled to test that my controller is correctly setting current_user > on its appropriate actions. Does this seem reasonable? If so, what's > the proper way to test it? Seems reasonable to me. You could test with either an interaction based approach (use mocks and stubs to confirm that @object receives the "created_by" message with the expected param) or a state based approach (hit the controller action and then inspect the system state afterwards to confirm that it is in the expected state). Interaction based approach: - may seem like more work due to the set-up of the mocks and stubs - runs faster because you can make it so that your controller test doesn't even hit the database - may cause you to replicate internal implementation details in your tests - may shield you from finding out about actual breakage in your system because it insulates your controller from the actual API on the real mocked/stubbed class State based approach: - may seem like less work due to easier set-up - may run slower, which can be important if you have an enormous spec suite - helps focus your specs on externally observable behavior rather than internal implementation details - couples your controller tests to your actual model instances, so breakage in your models will cause more than just model specs to fail Personally I prefer a state based approach in general, but I look at things on a case-by-case basis. Generally if I pick the wrong one I soon find out about it because the specs I end up writing are stomach-churning. And there is a feedback loop here too: if _both_ of these approaches seem difficult, then it is a sign that the code you're testing could probably be rethought to make it more easily testable. Cheers, Wincent From win at wincent.com Thu Jul 8 13:15:52 2010 From: win at wincent.com (Wincent Colaiuta) Date: Thu, 8 Jul 2010 19:15:52 +0200 Subject: [rspec-users] rspec-rails how to selectively turn on csrf protection for controller specs? In-Reply-To: References: Message-ID: <208AC8B2-D7D2-4769-A88E-114B50284758@wincent.com> El 08/07/2010, a las 18:36, nruth escribi?: > I'm setting up a Paypal IPN listener and need the create action to not > use rails' default CSRF protection. > > I've got that working fine & test it actually works with cucumber > (where I've turned CSRF back on, since it's full-stack testing) but > would like my controller spec to mention the need for > protect_from_forgery :except => [:create] (and fail when it's not > set). > > I've not had any luck with telling the controller or > ActionController::Base to use forgery protection in the spec and am a > bit stuck. > > Has anyone done this before, or do any of these look possible: > > * reload the rails app for part of the spec, using a different rails > initializer (i.e. without > config.action_controller.allow_forgery_protection = false as in > environments/test.rb) > * tell the controller to use forgery protection despite it being > turned off in the rails test environment config (haven't had any luck > with this so far). > * have some specs split off from the main specs which run in a > different rails environment, e.g. test-with-csrf rather than test. > > versions: rails 2.3.8, rspec 1.3.0, rspec-rails 1.3.2 > > Any help or pointers to old topics would be greatly appreciated, > google made this look a bit unexplored beyond "rails fixes csrf by > default, turn off in tests". I think Cucumber is the right level to test this at. But if you really, really want to test it at the RSpec level, take a look at what the protect_from_forgery method actually does: actionpack/lib/action_controller/metal/request_forgery_protection.rb It boils down to this: before_filter :verify_authenticity_token, options So you could introspect the controller and ask it what its before_filters are, and see if "verify_authenticity_token" is present or absent. But I fear it would require some ugly hacking via instance_variable_get, which is why I say that Cucumber is the right level to test this sort of thing on. Cheers, Wincent From dchelimsky at gmail.com Thu Jul 8 13:45:50 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 8 Jul 2010 12:45:50 -0500 Subject: [rspec-users] experimental branch with no at_exit hook Message-ID: <4F083A03-2C99-47C5-A205-D7AE550E9E1F@gmail.com> Hey all, I've got an experimental branch of rspec-core-2 that removes the at_exit hook: http://github.com/rspec/rspec-core/tree/no-at-exit. It works just fine with the rake and rspec commands, as well as spork. You can use it with the ruby command if you include "-S rspec" (avoiding this was one of the reasons for the at_exit hook in the first place). The only case in which I'm unable to get it to work is with the updated TextMate bundle (http://github.com/rspec/rspec-tmbundle). I'll start a separate thread for that issue. This is a big change, so I don't want to merge it to master without some serious field testing. If any of you care to point your Gemfile at the no-at-exit branch and try it out on your apps, feedback would be greatly appreciated. Thanks, David From dchelimsky at gmail.com Thu Jul 8 13:53:35 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 8 Jul 2010 12:53:35 -0500 Subject: [rspec-users] RSpec.tmbundle failure after removing at_exit hook Message-ID: <3430A05F-1545-4A74-ABB0-2E61219E5200@gmail.com> Hey all, Following up on the problem with textmate after removing the at_exit hook (see http://groups.google.com/group/rspec/browse_thread/thread/37bbe78aa52682b0): The problem is that the file(s) do(es) not get loaded by the rspec runner. They appear to be required by TextMate prior to invoking the rspec runner, so when they are required, Ruby does not reload them. I tried overriding the require_files_to_run method from within spec/mate/runner.rb: ::RSpec::Core::Configuration.class_eval do def require_files_to_run do files_to_run.each {|f| load f} end end That didn't work, but if I changed "files_to_run.each {|f| load f}" to "load ENV['TM_FILEPATH']", it worked just fine for the cases in which we only care about one file: ::RSpec::Core::Configuration.class_eval do def require_files_to_run do load ENV['TM_FILEPATH'] end end This is not a solution, but just something I encountered while trying to understand the problem. I then verified that require_files_to_run.first == ENV['TM_FILEPATH'], and now I am absolutely mystified. If anyone is interested in helping solve this, grab the http://github.com/rspec/rspec-core/tree/no-at-exit branch of rspec-core and master from http://github.com/rspec/rspec-tmbundle. TIA for any help. Cheers, David From hooligan495 at gmail.com Thu Jul 8 15:29:04 2010 From: hooligan495 at gmail.com (Jay) Date: Thu, 8 Jul 2010 12:29:04 -0700 (PDT) Subject: [rspec-users] RSpec TM bundle question Message-ID: <6d93d450-0c87-4708-932f-cb9944415dbe@w31g2000yqb.googlegroups.com> does the RSpec TM bundle require that one have the RSpec 2 prerelease version installed? When I try to use the latest TMBundle I get a can't find rspec/core error From hooligan495 at gmail.com Thu Jul 8 15:37:38 2010 From: hooligan495 at gmail.com (Jay McGaffigan) Date: Thu, 8 Jul 2010 15:37:38 -0400 Subject: [rspec-users] RSpec TM bundle question In-Reply-To: <6d93d450-0c87-4708-932f-cb9944415dbe@w31g2000yqb.googlegroups.com> References: <6d93d450-0c87-4708-932f-cb9944415dbe@w31g2000yqb.googlegroups.com> Message-ID: a little more investigation shows that the bundle is really having trouble loading the 'spec/autorun' file in mate.rb it appears that rubygems is not loaded (I'm not using bundler on this project (yet)). If I mod mate.rb to require rubygems before requiring spec/autorun things seem to work... Not sure this is the right approach tho... I've got rspec 1.3.0 installed. On Thu, Jul 8, 2010 at 3:29 PM, Jay wrote: > does the RSpec TM bundle require that one have the RSpec 2 prerelease > version installed? ?When I try to use the latest TMBundle I get a > can't find rspec/core error > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From dchelimsky at gmail.com Thu Jul 8 15:55:10 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 8 Jul 2010 14:55:10 -0500 Subject: [rspec-users] RSpec TM bundle question In-Reply-To: References: <6d93d450-0c87-4708-932f-cb9944415dbe@w31g2000yqb.googlegroups.com> Message-ID: <2C365E63-23E5-426A-8E9F-697FAA772363@gmail.com> On Jul 8, 2010, at 2:37 PM, Jay McGaffigan wrote: > a little more investigation shows that the bundle is really having > trouble loading the 'spec/autorun' file in mate.rb > > it appears that rubygems is not loaded (I'm not using bundler on this > project (yet)). > > If I mod mate.rb to require rubygems before requiring spec/autorun > things seem to work... > > Not sure this is the right approach tho... > > > > I've got rspec 1.3.0 installed. Try setting your TM_RSPEC_HOME to point to wherever rspec-1.3.0 is installed on your file system. It should work if that's there and there's no Gemfile in your project. > On Thu, Jul 8, 2010 at 3:29 PM, Jay wrote: >> does the RSpec TM bundle require that one have the RSpec 2 prerelease >> version installed? When I try to use the latest TMBundle I get a >> can't find rspec/core error >> >> _______________________________________________ >> 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 From phillipkoebbe at gmail.com Thu Jul 8 21:49:42 2010 From: phillipkoebbe at gmail.com (Phillip Koebbe) Date: Thu, 08 Jul 2010 20:49:42 -0500 Subject: [rspec-users] rspec-rails how to selectively turn on csrf protection for controller specs? In-Reply-To: <208AC8B2-D7D2-4769-A88E-114B50284758@wincent.com> References: <208AC8B2-D7D2-4769-A88E-114B50284758@wincent.com> Message-ID: <4C368036.6050801@gmail.com> On 2010-07-08 12:15 PM, Wincent Colaiuta wrote: > El 08/07/2010, a las 18:36, nruth escribi?: > >> I'm setting up a Paypal IPN listener and need the create action to not >> use rails' default CSRF protection. >> >> I've got that working fine& test it actually works with cucumber >> (where I've turned CSRF back on, since it's full-stack testing) but >> would like my controller spec to mention the need for >> protect_from_forgery :except => [:create] (and fail when it's not >> set). >> >> I've not had any luck with telling the controller or >> ActionController::Base to use forgery protection in the spec and am a >> bit stuck. >> >> Has anyone done this before, or do any of these look possible: >> >> * reload the rails app for part of the spec, using a different rails >> initializer (i.e. without >> config.action_controller.allow_forgery_protection = false as in >> environments/test.rb) >> * tell the controller to use forgery protection despite it being >> turned off in the rails test environment config (haven't had any luck >> with this so far). >> * have some specs split off from the main specs which run in a >> different rails environment, e.g. test-with-csrf rather than test. >> >> versions: rails 2.3.8, rspec 1.3.0, rspec-rails 1.3.2 >> >> Any help or pointers to old topics would be greatly appreciated, >> google made this look a bit unexplored beyond "rails fixes csrf by >> default, turn off in tests". > I think Cucumber is the right level to test this at. But if you really, really want to test it at the RSpec level, take a look at what the protect_from_forgery method actually does: > > actionpack/lib/action_controller/metal/request_forgery_protection.rb > > It boils down to this: > > before_filter :verify_authenticity_token, options > > So you could introspect the controller and ask it what its before_filters are, and see if "verify_authenticity_token" is present or absent. But I fear it would require some ugly hacking via instance_variable_get, which is why I say that Cucumber is the right level to test this sort of thing on. > Actually, it's not that difficult. I have a macro (or whatever the proper term is) to spec the existence of before_filters. It looks like: def should_have_before_filters(*filters) filters.each do |filter| it "should have before_filter #{filter}" do controller.class.before_filters.should include(filter) end end end alias_method :should_have_before_filter, :should_have_before_filters This is RSpec 1.3.x for Rails 2.3.x. I have no idea if this will work in RSpec 2.x and Rails 3. Peace, Phillip From frankjmattia at gmail.com Thu Jul 8 22:25:31 2010 From: frankjmattia at gmail.com (Frank J. Mattia) Date: Thu, 8 Jul 2010 19:25:31 -0700 (PDT) Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> Message-ID: <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> > > My controller does something like this for create > > @object = Object.new(params[:object]) > > @object.created_by = current_user > > if @object.save... yadda yadda yadda... > > > I have my model spec testing for the presence of created_by but I feel > > compelled to test that my controller is correctly setting current_user > > on its appropriate actions. Does this seem reasonable? If so, what's > > the proper way to test it? > > Seems reasonable to me. You could test with either an interaction based approach (use mocks and stubs to confirm that @object receives the "created_by" message with the expected param) or a state based approach (hit the controller action and then inspect the system state afterwards to confirm that it is in the expected state). What I was trying to do on my own felt a lot like what you're calling an interaction based approach. I want to leave the behavior testing of my app to cuke features and I'm thinking that if I'm writing a controller spec, then it would probably be right to test the internals of my controllers. (As an aside, I've only been using RSpec for ~3 weeks now and testing in general for maybe a month. All of this is pretty new to me... I find myself quickly becoming 'opinionated' about things so if any of this sounds like nonsense, a pointer in a good direction would be happily accepted.) Here's a stripped down excerpt from my controller spec. I know how Order.should_receive(:method) works, but how do I translate that to an instance variable? I've tried assigns(:order).should_receive to no avail. Also, where do I put it? Above the post line won't work because @order doesn't exist but after doesn't work either because my action has already been run. describe OrdersController, :type => :controller do context "when a user who is authenticated" do before(:each) do sign_in_user end context "requests POST /orders" do context "with valid parameters" do before(:each) do Order.stub(:new) { mock_order(:save => true) } end it "should explicitly set created_by" do post :create end end end end end I'm still reading the docs and will make some more attempts to get it right. Thank you for your help. Cheers, - FJM From frankjmattia at gmail.com Fri Jul 9 00:07:51 2010 From: frankjmattia at gmail.com (Frank J. Mattia) Date: Thu, 8 Jul 2010 21:07:51 -0700 (PDT) Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> Message-ID: > Here's a stripped down excerpt from my controller spec. I know how > Order.should_receive(:method) works, but how do I translate that to an > instance variable? I've tried assigns(:order).should_receive to no > avail. Also, where do I put it? Above the post line won't work because > @order doesn't exist but after doesn't work either because my action > has already been run. > > describe OrdersController, :type => :controller do > ? context "when a user who is authenticated" do > ? ? before(:each) do > ? ? ? sign_in_user > ? ? end > ? ? context "requests POST /orders" do > ? ? ? context "with valid parameters" do > ? ? ? ? before(:each) do > ? ? ? ? ? Order.stub(:new) { mock_order(:save => true) } > ? ? ? ? end > > ? ? ? ? it "should explicitly set created_by" do > ? ? ? ? ? post :create > ? ? ? ? end > ? ? ? end > ? ? end > ? end > end it "should explicitly set created_by" do controller.stub(:current_user) { mock_user } mock_order.should_receive(:created_by=).with(mock_user) post :create end This is my newly working spec. Does this look well thought out or is there some glaring pitfall to doing it this way? Cheers, - FJM From win at wincent.com Fri Jul 9 01:56:12 2010 From: win at wincent.com (Wincent Colaiuta) Date: Fri, 9 Jul 2010 07:56:12 +0200 Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> Message-ID: <610AA529-9854-44F4-864E-AC92A562DF67@wincent.com> El 09/07/2010, a las 04:25, Frank J. Mattia escribi?: >> Seems reasonable to me. You could test with either an interaction based approach (use mocks and stubs to confirm that @object receives the "created_by" message with the expected param) or a state based approach (hit the controller action and then inspect the system state afterwards to confirm that it is in the expected state). > > What I was trying to do on my own felt a lot like what you're calling > an interaction based approach. I want to leave the behavior testing of > my app to cuke features and I'm thinking that if I'm writing a > controller spec, then it would probably be right to test the internals > of my controllers. I wouldn't say that "behavior" is only for Cucumber. Back when Cucumber hadn't even been imagined yet, RSpec was created as a "Behavior-Driven Development" library. Behavior has always been central to what we do with RSpec, even at the lowest levels. I think an important question to ask yourself when writing specs is "_Why_ am I doing this?", and that leads on to "_What_ am I interested in specifying here?". For me it's _all_ about behavior. The specs have two purposes, then: to document/show the behavior (when read), and to confirm/test the behavior (when executed). If I find myself writing a test that neither shows nor tests behavior, then I probably shouldn't be writing it. So, with the focus always on the behavior of the action, you can proceed to do either interaction-based or state-based testing, depending on what feels right for each particular case. As I mentioned in my earlier email, there are costs and benefits of each approach, and long running debates about which method to use when, but I think the important thing is to always try to use the best tool for the job at hand. > (As an aside, I've only been using RSpec for ~3 > weeks now and testing in general for maybe a month. All of this is > pretty new to me... I find myself quickly becoming 'opinionated' about > things so if any of this sounds like nonsense, a pointer in a good > direction would be happily accepted.) I think the best way to learn is to do what you're already doing: writing specs (lots of them), _thinking_ about what you're doing, and when you have doubts asking questions or looking for better ways. As time goes by you'll not only get better at it, but your thinking will probably evolve too. I know I've gone back and forth many times over the years, and sometimes I get a surprise when I stumble over an old blog post of mine on testing and see what I posted. I think if you look at what the most influential people in the Ruby/RSpec testing community have been saying over the years, you'll see how _their_ ideas have been metamorphosing and changing over the years too. It's a natural part of thoughtful testing, I think. El 09/07/2010, a las 06:07, Frank J. Mattia escribi?: > it "should explicitly set created_by" do > controller.stub(:current_user) { mock_user } > mock_order.should_receive(:created_by=).with(mock_user) > post :create > end > > This is my newly working spec. Does this look well thought out or is > there some glaring pitfall to doing it this way? Well, this is the way mocking and stubbing works. If you want to set an expectation on an object that doesn't exist yet at the time you're setting up the spec, you have to "chain" things so as to inject a mock of your own at the right place, which you've done here. The amount of work you have to do setting this up will vary from case to case. This is one of the costs of the interaction-based approached, and you have to weigh up that cost against the benefits. Cheers, Wincent From lists at ruby-forum.com Fri Jul 9 03:19:31 2010 From: lists at ruby-forum.com (Juanma Cervera) Date: Fri, 9 Jul 2010 09:19:31 +0200 Subject: [rspec-users] Testing equality In-Reply-To: <6402C201-34FF-434C-86AC-92F517BCC391@gmail.com> References: <6948144278486ee2d0d3d76fe7d55eae@ruby-forum.com> <6402C201-34FF-434C-86AC-92F517BCC391@gmail.com> Message-ID: David Chelimsky wrote: > On Jul 8, 2010, at 5:04 AM, Juanma Cervera wrote: > >> end. >> >> FAILS >> >> This fails because the object expected is different from the object >> gotten, and the only difference are the BigDecimal attributes, that are >> different objects, even though they have the same value. > > rspec delegates ==() to the objects being compared. It's up to library > providers and users to override ==() in a way that is sane in a given > context. Assuming a single BigDecimal attr named amount, something like > this: > > def ==(other) > self.attributes.merge(:amount => BigDecimal.new(self.amount.to_s)) == > other.attributes.merge(:amount => BigDecimal.new(other.amount.to_s)) > end > > HTH, > David Thanks for your answer David, but I think there is a problem. The assertion that fails has nothing to do with the BidDecimal types, but with the created_at and updated_at timestamps I have try this: v = Factory.create(:my_object) f = MyObject.first v.should == f ==> This fails v.amount.should == f.amount ==> This works But... v.updated_at.should == f.updated_at RSpec::Expectations::ExpectationNotMetError: expected: Fri, 09 Jul 2010 06:57:48 UTC +00:00, got: Fri, 09 Jul 2010 06:57:48 UTC +00:00 (using ==) Diff: from /home/jmcervera/.rvm/gems/ruby-1.8.7-p299 at rails3/gems/rspec-expectations-2.0.0.beta.15/lib/rspec/expectations/fail_with.rb:29:in `fail_with' from /home/jmcervera/.rvm/gems/ruby-1.8.7-p299 at rails3/gems/rspec-expectations-2.0.0.beta.15/lib/rspec/matchers/operator_matcher.rb:39:in `fail_with_message' from /home/jmcervera/.rvm/gems/ruby-1.8.7-p299 at rails3/gems/rspec-expectations-2.0.0.beta.15/lib/rspec/matchers/operator_matcher.rb:61:in `__delegate_operator' from /home/jmcervera/.rvm/gems/ruby-1.8.7-p299 at rails3/gems/rspec-expectations-2.0.0.beta.15/lib/rspec/matchers/operator_matcher.rb:51:in `eval_match' from /home/jmcervera/.rvm/gems/ruby-1.8.7-p299 at rails3/gems/rspec-expectations-2.0.0.beta.15/lib/rspec/matchers/operator_matcher.rb:29:in `==' from (irb):41 -- Posted via http://www.ruby-forum.com/. From lists at ruby-forum.com Fri Jul 9 03:37:05 2010 From: lists at ruby-forum.com (Juanma Cervera) Date: Fri, 9 Jul 2010 09:37:05 +0200 Subject: [rspec-users] Testing equality In-Reply-To: References: <6948144278486ee2d0d3d76fe7d55eae@ruby-forum.com> <6402C201-34FF-434C-86AC-92F517BCC391@gmail.com> Message-ID: <0f0ccf423496ce8dce44603c23303c82@ruby-forum.com> The updated_at has class ActiveSupport::TimeWithZone v.updated_at.should == f.updated_at fails v.updated_at.to_datetime.should == f.to_datetime.updated_at fails v.updated_at.to_s.should == f.updated_at.to_s works v.updated_at.to_i.should == f.updated_at.to_i works And adding this method to the model doesn't work either. def ==(other) (self.attributes.merge(:created_at => Datetime.new(self.created_at.to_s), :updated_at => Datetime.new(self.updated_at.to_s)) == (other.attributes.merge(:created_at => Datetime.new(self.other_at.to_s), :updated_at => Datetime.new(self.other_at.to_s)) end Thanks Juanma -- Posted via http://www.ruby-forum.com/. From garren.smith at gmail.com Fri Jul 9 07:59:51 2010 From: garren.smith at gmail.com (garren) Date: Fri, 9 Jul 2010 04:59:51 -0700 (PDT) Subject: [rspec-users] Setting up rspec-rails for hacking In-Reply-To: References: Message-ID: <5917e287-1431-4f0a-86ee-e69f1dda0335@t10g2000yqg.googlegroups.com> I've followed the instructions to install the dev environment, when I run rake install I get this for the rspec-rails: cp ./templates/Gemfile ./tmp/example_app/ rake rails:template LOCATION='../../templates/generate_stuff.rb' (in /Users/garren/webdev/rspec-dev/repos/rspec-rails/tmp/example_app) generate rspec:install generate controller wombats index generate controller welcome index generate integration_test widgets generate mailer Notifications signup generate model thing name:string generate helper things generate scaffold widget name:string category:string instock:boolean generate observer widget generate scaffold gadget run rake db:migrate from "." run rake db:test:prepare from "." /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -I "/Library/Ruby/Gems/1.8/gems/cucumber-0.8.3/lib:lib" "/Library/Ruby/ Gems/1.8/gems/cucumber-0.8.3/bin/cucumber" --format progress Using the default profile... You have already activated rspec-expectations 2.0.0.beta.13, but your Gemfile requires rspec-expectations 2.0.0.beta.16. Consider using bundle exec. (Gem::LoadError) Any ideas on how to fix this? On Jul 7, 12:34?pm, David Chelimsky wrote: > On Jul 7, 2010, at 5:26 AM, Trevor Lalish-Menagh wrote: > > >> Did you know about the rspec-dev meta project? > > >>http://github.com/rspec/rspec-dev > > > That is great. I should have looked for that before setting this up. I just didn't think about it. > > >> Perhaps we should update the rspec-* READMEs with a point back to rspec-dev so that people know about it? > > > Good call. That would help. > > Done: > > http://github.com/rspec/rspechttp://github.com/rspec/rspec-corehttp://github.com/rspec/rspec-expectationshttp://github.com/rspec/rspec-mockshttp://github.com/rspec/rspec-rails > > Cheers, > David > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From frankjmattia at gmail.com Fri Jul 9 08:29:37 2010 From: frankjmattia at gmail.com (Frank J. Mattia) Date: Fri, 9 Jul 2010 05:29:37 -0700 (PDT) Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <610AA529-9854-44F4-864E-AC92A562DF67@wincent.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> <610AA529-9854-44F4-864E-AC92A562DF67@wincent.com> Message-ID: <4baee084-e4a5-460d-921d-cd7d714b2d13@r27g2000yqb.googlegroups.com> > > > Seems reasonable to me. You could test with either an interaction based > > > approach (use mocks and stubs to confirm that @object receives the > > > "created_by" message with the expected param) or a state based approach > > > (hit the controller action and then inspect the system state afterwards > > > to confirm that it is in the expected state). > > > What I was trying to do on my own felt a lot like what you're calling > > an interaction based approach. I want to leave the behavior testing of > > my app to cuke features and I'm thinking that if I'm writing a > > controller spec, then it would probably be right to test the internals > > of my controllers. > > I wouldn't say that "behavior" is only for Cucumber. Back when Cucumber > hadn't even been imagined yet, RSpec was created as a "Behavior-Driven > Development" library. Behavior has always been central to what we do > with RSpec, even at the lowest levels. > > I think an important question to ask yourself when writing specs is > "_Why_ am I doing this?", and that leads on to "_What_ am I interested > in specifying here?". For me it's _all_ about behavior. In retrospect, that's absolutely right. I think what I should have said was I want separation of granularity in my behaviors. The model being the most fine grained and the features being the most coarse - with just enough overlap as to not leave any holes but not so much as to make senseless duplication. > The specs have two purposes, then: to document/show the behavior (when read), > and to confirm/test the behavior (when executed). If I find myself writing > a test that neither shows nor tests behavior, then I probably shouldn't be writing it. That's been a good barometer for me too. > > it "should explicitly set created_by" do > > ?controller.stub(:current_user) { mock_user } > > ?mock_order.should_receive(:created_by=).with(mock_user) > > ?post :create > > end > > > This is my newly working spec. Does this look well thought out or is > > there some glaring pitfall to doing it this way? > > Well, this is the way mocking and stubbing works. If you want to set an expectation on an object that doesn't exist yet at the time you're setting up the spec, you have to "chain" things so as to inject a mock of your own at the right place, which you've done here. The amount of work you have to do setting this up will vary from case to case. > > This is one of the costs of the interaction-based approached, and you have to weigh up that cost against the benefits. Out of curiosity, how would you do this with a state based approach? I've tried checking the value of created_by after post :create but my assign(:order) has no idea what :created_by is. assigns(:order).created_by.should eq(mock_current_user) just doesn't do what I thought it would. Cheers, - FJM From dchelimsky at gmail.com Fri Jul 9 09:06:28 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 9 Jul 2010 08:06:28 -0500 Subject: [rspec-users] Setting up rspec-rails for hacking In-Reply-To: <5917e287-1431-4f0a-86ee-e69f1dda0335@t10g2000yqg.googlegroups.com> References: <5917e287-1431-4f0a-86ee-e69f1dda0335@t10g2000yqg.googlegroups.com> Message-ID: On Jul 9, 2010, at 6:59 AM, garren wrote: > > > On Jul 7, 12:34 pm, David Chelimsky wrote: >> On Jul 7, 2010, at 5:26 AM, Trevor Lalish-Menagh wrote: >> >>>> Did you know about the rspec-dev meta project? >> >>>> http://github.com/rspec/rspec-dev >> >>> That is great. I should have looked for that before setting this up. I just didn't think about it. >> >>>> Perhaps we should update the rspec-* READMEs with a point back to rspec-dev so that people know about it? >> >>> Good call. That would help. >> >> Done: >> >> http://github.com/rspec/rspechttp://github.com/rspec/rspec-corehttp://github.com/rspec/rspec-expectationshttp://github.com/rspec/rspec-mockshttp://github.com/rspec/rspec-rails > > I've followed the instructions to install the dev environment, when I > run rake install I get this for the rspec-rails: > cp ./templates/Gemfile ./tmp/example_app/ > rake rails:template LOCATION='../../templates/generate_stuff.rb' > (in /Users/garren/webdev/rspec-dev/repos/rspec-rails/tmp/example_app) > generate rspec:install > generate controller wombats index > generate controller welcome index > generate integration_test widgets > generate mailer Notifications signup > generate model thing name:string > generate helper things > generate scaffold widget name:string category:string > instock:boolean > generate observer widget > generate scaffold gadget > run rake db:migrate from "." > run rake db:test:prepare from "." > /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -I > "/Library/Ruby/Gems/1.8/gems/cucumber-0.8.3/lib:lib" "/Library/Ruby/ > Gems/1.8/gems/cucumber-0.8.3/bin/cucumber" --format progress > Using the default profile... > You have already activated rspec-expectations 2.0.0.beta.13, but your > Gemfile requires rspec-expectations 2.0.0.beta.16. Consider using > bundle exec. (Gem::LoadError) > > Any ideas on how to fix this? Looks like a change to aruba broke the rspec build :) Looking into it now. PS - please post at the bottom or inline instead of top-posting: http://idallen.com/topposting.html From win at wincent.com Fri Jul 9 09:38:20 2010 From: win at wincent.com (Wincent Colaiuta) Date: Fri, 9 Jul 2010 15:38:20 +0200 Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <4baee084-e4a5-460d-921d-cd7d714b2d13@r27g2000yqb.googlegroups.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> <610AA529-9854-44F4-864E-AC92A562DF67@wincent.com> <4baee084-e4a5-460d-921d-cd7d714b2d13@r27g2000yqb.googlegroups.com> Message-ID: <4D5B4912-9620-4641-96E3-8ED928BF1F57@wincent.com> El 09/07/2010, a las 14:29, Frank J. Mattia escribi?: >>> it "should explicitly set created_by" do >>> controller.stub(:current_user) { mock_user } >>> mock_order.should_receive(:created_by=).with(mock_user) >>> post :create >>> end >> >>> This is my newly working spec. Does this look well thought out or is >>> there some glaring pitfall to doing it this way? >> >> Well, this is the way mocking and stubbing works. If you want to set an expectation on an object that doesn't exist yet at the time you're setting up the spec, you have to "chain" things so as to inject a mock of your own at the right place, which you've done here. The amount of work you have to do setting this up will vary from case to case. >> >> This is one of the costs of the interaction-based approached, and you have to weigh up that cost against the benefits. > > Out of curiosity, how would you do this with a state based approach? > I've tried checking the value of created_by after post :create but my > assign(:order) has no idea what :created_by is. > assigns(:order).created_by.should eq(mock_current_user) just doesn't > do what I thought it would. Ok, some qualifications: - I use factories heavily (in this example Factory Girl) to make it easier to write tests. I don't worry about the slowness of using real model instances until the spec suite actually becomes large enough for it to be a problem. I also don't worry about the risk of cascading failures (broken model breaks controller spec) because I value the simplicity that comes with keeping mocking and stubbing to a minimum in the specs, and I am wary of the insulation that mocking and stubbing bring and can actually hide real failures (eg. API changes but spec keeps passing anyway). I still do mock and stub, but generally only where it is not easier to just verify state (and it often is easier). - I use RR for mocking because I like the syntax. Even in a state-based approach, you'll see I have to stub out the "current_user" method on the controller. - I use a "before" block that sets up @user, @params, and does the stubbing, so that I can reuse the same stuff in many different "it" blocks. - And I try to keep each "it" block as short as possible, just do the post then inspect the state afterwards. In this case the state that I am checking for is the externally visible stuff like what got assigned (assigns), what got rendered (render_template) or redirected (redirect_to), what flash or cookies got set, and so on. If need be, I can query the database. - And finally, note that this is written for Rails 3/RSpec 2, which I've been using solidly for the last month and have now forgotten what Rails 2/RSpec 1 specs looked like! So with all that said, this is more or less what my state-based approach would look like: before do @user = User.make! stub(controller).current_user { @user } @params = { :post => { :title => 'foo', :body => 'bar' } } end it 'should set created_by' do post :create, @params assigns[:post].created_by.should == @user end ... The controller/action is treated as a "black box" which I never look inside. Each "it" block basically just follows this pattern: 1. Feed params into the black box 2. Check _one_ piece of state afterwards By trying to keep only one "should" assertion in each "it" block I get nice granularity in the event of failure. It is not "better" nor "the right" way, it is just "a" way of doing it. I've also written controller specs where I ended up mocking left, right and center, but if I can take the state-based approach I generally prefer it. The app I'm currently working on has about 3,000 examples, and the suite runs fast enough that I don't yet feel the need to change my emphasis away from state-based testing. Cheers, Wincent From daniel.amselem at gmail.com Fri Jul 9 14:45:59 2010 From: daniel.amselem at gmail.com (Daniel Salmeron Amselem) Date: Fri, 9 Jul 2010 11:45:59 -0700 (PDT) Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store Message-ID: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> I've been trying to test a very simple action on a controller with this setup: rspec 1.3.0 ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] Rails 2.3.8 devise 1.0.8 And this is the test: before :each do @member = Factory.create(:member) sign_in @member @person = Person.new end it "should render form for a new person on GET people#new" do current_member.should_receive(:build_person).and_return(@person) get :new assigns[:person].should == @person response.should be_success response.should render_template("new") end This test creates a user, which is stored in the database with a correct password. Running this test results in this error: 1) NoMethodError in 'PeopleController Methods should render form for a new person on GET people#new' You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]= /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ session_serializer.rb:25:in `store' /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: 73:in `sign_in' /Users/damselem/Documents/project/spec/controllers/ people_controller_spec.rb:15: Finished in 0.625754 seconds 23 examples, 1 failure I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ session_serializer.rb and I changed the file in order to print out some values: def store(user, scope) return unless user p scope p key_for(scope) p user p serialize(user) p session session[key_for(scope)] = serialize(user) end When running the test again I get: :member "warden.user.member.key" Member id: 1, email: "member2 at hv_club.com", encrypted_password: "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, confirmation_sent_at: nil, reset_password_token: nil, remember_token: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 16:45:44" [Member(id: integer, email: string, encrypted_password: string, password_salt: string, confirmation_token: string, confirmed_at: datetime, confirmation_sent_at: datetime, reset_password_token: string, remember_token: string, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime, updated_at: datetime), 1] nil So it seems session is not initialized. Any ideas on how to fix this? BTW, I already contacted Jose Valim through GitHub and he recommended me to post my question in this group. http://github.com/plataformatec/devise/issues/issue/374 Thanks. From patgannon at gmail.com Fri Jul 9 20:37:52 2010 From: patgannon at gmail.com (Patrick Gannon) Date: Fri, 9 Jul 2010 17:37:52 -0700 Subject: [rspec-users] [Rails] Stubbed static methods are bleeding over into other specs and making them fail In-Reply-To: <2F30C790-F219-4DD4-8932-8238E66C752D@gmail.com> References: <2F30C790-F219-4DD4-8932-8238E66C752D@gmail.com> Message-ID: On Mon, Jul 5, 2010 at 1:26 PM, David Chelimsky wrote: > I just pushed what I believe to be a fix for this - please try pointing > Gemfile to the git repos again. It should work if you do this with all of > them: > > gem "rspec-rails", :git => "git://github.com/rspec/rspec-rails.git" > gem "rspec", :git => "git://github.com/rspec/rspec.git" > gem "rspec-core", :git => "git://github.com/rspec/rspec-core.git" > gem "rspec-expectations", :git => " > git://github.com/rspec/rspec-expectations.git" > gem "rspec-mocks", :git => "git://github.com/rspec/rspec-mocks.git" > > Let me know if it works out. > > Hi David, I just got a chance to try this, and ran into more problems. Prior to trying this, we were running RSpec2 beta 13. When I changed our Gemfile to depend on 'edge' RSpec et al (as you suggested above), I get a very strange error when I run rake (after doing a 'bundle install'). The same error occurs after I tell it specifically to use beta 16 (rather than 'edge'). It seems to somehow not be able to find the bundler gem when it runs the main bundler script from within rake: C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:779:in `report_activate_error': Could not find RubyGem bundler (>= 0) (Gem::LoadError) from C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:214:in `activate' from C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:1082:in `gem' from C:/Ruby187/bin/bundle:18 rake aborted! bundle exec C:/Ruby187/bin/ruby.exe -Ilib -Ispec "./spec/controllers/discrepancies_controller_spec.rb" *(...spec names omitted..)* failed When I downgrade back to beta 13, everything works again. I can't seem to figure out why it wouldn't be able to find the bundler gem (since obviously bundler is installed), so I cannot say whether or not your fix for the stubbing issue solved my problem. The stack trace (resulting from running rake with "--trace") and my current list of installed gems (via "bundle list") is here: http://gist.github.com/470278 (sorry for the line breaks) Thanks for your help! Pat Gannon -------------- next part -------------- An HTML attachment was scrubbed... URL: From frankjmattia at gmail.com Fri Jul 9 23:13:29 2010 From: frankjmattia at gmail.com (Frank J. Mattia) Date: Fri, 9 Jul 2010 20:13:29 -0700 (PDT) Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <4D5B4912-9620-4641-96E3-8ED928BF1F57@wincent.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> <610AA529-9854-44F4-864E-AC92A562DF67@wincent.com> <4baee084-e4a5-460d-921d-cd7d714b2d13@r27g2000yqb.googlegroups.com> <4D5B4912-9620-4641-96E3-8ED928BF1F57@wincent.com> Message-ID: <72a504d5-6df1-428d-895c-2e93df3e6971@r27g2000yqb.googlegroups.com> > >>> it "should explicitly set created_by" do > >>> ?controller.stub(:current_user) { mock_user } > >>> ?mock_order.should_receive(:created_by=).with(mock_user) > >>> ?post :create > >>> end > > >>> This is my newly working spec. Does this look well thought out or is > >>> there some glaring pitfall to doing it this way? > > >> Well, this is the way mocking and stubbing works. If you want to set an expectation on an object that doesn't exist yet at the time you're setting up the spec, you have to "chain" things so as to inject a mock of your own at the right place, which you've done here. The amount of work you have to do setting this up will vary from case to case. > > >> This is one of the costs of the interaction-based approached, and you have to weigh up that cost against the benefits. > > > Out of curiosity, how would you do this with a state based approach? > > I've tried checking the value of created_by after post :create but my > > assign(:order) has no idea what :created_by is. > > assigns(:order).created_by.should eq(mock_current_user) just doesn't > > do what I thought it would. > > Ok, some qualifications: > > - I use factories heavily (in this example Factory Girl) to make it easier to write tests. I don't worry about the slowness of using real model instances until the spec suite actually becomes large enough for it to be a problem. I also don't worry about the risk of cascading failures (broken model breaks controller spec) because I value the simplicity that comes with keeping mocking and stubbing to a minimum in the specs, and I am wary of the insulation that mocking and stubbing bring and can actually hide real failures (eg. API changes but spec keeps passing anyway). I still do mock and stub, but generally only where it is not easier to just verify state (and it often is easier). > > - I use RR for mocking because I like the syntax. Even in a state-based approach, you'll see I have to stub out the "current_user" method on the controller. > > - I use a "before" block that sets up @user, @params, and does the stubbing, so that I can reuse the same stuff in many different "it" blocks. > > - And I try to keep each "it" block as short as possible, just do the post then inspect the state afterwards. In this case the state that I am checking for is the externally visible stuff like what got assigned (assigns), what got rendered (render_template) or redirected (redirect_to), what flash or cookies got set, and so on. If need be, I can query the database. > > - And finally, note that this is written for Rails 3/RSpec 2, which I've been using solidly for the last month and have now forgotten what Rails 2/RSpec 1 specs looked like! > > So with all that said, this is more or less what my state-based approach would look like: > > ? before do > ? ? @user = User.make! > ? ? stub(controller).current_user { @user } > ? ? @params = { :post => { :title => 'foo', :body => 'bar' } } > ? end > > ? it 'should set created_by' do > ? ? post :create, @params > ? ? assigns[:post].created_by.should == @user > ? end > > ? ... > > The controller/action is treated as a "black box" which I never look inside. Each "it" block basically just follows this pattern: > > ? 1. Feed params into the black box > ? 2. Check _one_ piece of state afterwards > > By trying to keep only one "should" assertion in each "it" block I get nice granularity in the event of failure. > > It is not "better" nor "the right" way, it is just "a" way of doing it. I've also written controller specs where I ended up mocking left, right and center, but if I can take the state-based approach I generally prefer it. The app I'm currently working on has about 3,000 examples, and the suite runs fast enough that I don't yet feel the need to change my emphasis away from state-based testing. Thanks for all your help. I've been toying around with a few different approaches to these two ways and I'm starting to make sense of it all. I too have been using Factory Girl (after spending a day creating my own factory implementation and not knowing what it was). I can't say I'm sold on rr but it does look promising. After trying mocha for all of 32 seconds I just couldn't take it (any_instance made me twitch) and went back to rspec mocking & stubbing... I'll keep it in the back of my mind for a day that I'm feeling experimental. Anyway, thanks again. You've been a huge help. Cheers, - FJM From phillipkoebbe at gmail.com Fri Jul 9 23:29:36 2010 From: phillipkoebbe at gmail.com (Phillip Koebbe) Date: Fri, 09 Jul 2010 22:29:36 -0500 Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <4D5B4912-9620-4641-96E3-8ED928BF1F57@wincent.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> <610AA529-9854-44F4-864E-AC92A562DF67@wincent.com> <4baee084-e4a5-460d-921d-cd7d714b2d13@r27g2000yqb.googlegroups.com> <4D5B4912-9620-4641-96E3-8ED928BF1F57@wincent.com> Message-ID: <4C37E920.5070203@gmail.com> On 2010-07-09 8:38 AM, Wincent Colaiuta wrote: > El 09/07/2010, a las 14:29, Frank J. Mattia escribi?: > >>>> it "should explicitly set created_by" do >>>> controller.stub(:current_user) { mock_user } >>>> mock_order.should_receive(:created_by=).with(mock_user) >>>> post :create >>>> end >>>> This is my newly working spec. Does this look well thought out or is >>>> there some glaring pitfall to doing it this way? >>> Well, this is the way mocking and stubbing works. If you want to set an expectation on an object that doesn't exist yet at the time you're setting up the spec, you have to "chain" things so as to inject a mock of your own at the right place, which you've done here. The amount of work you have to do setting this up will vary from case to case. >>> >>> This is one of the costs of the interaction-based approached, and you have to weigh up that cost against the benefits. >> Out of curiosity, how would you do this with a state based approach? >> I've tried checking the value of created_by after post :create but my >> assign(:order) has no idea what :created_by is. >> assigns(:order).created_by.should eq(mock_current_user) just doesn't >> do what I thought it would. > Ok, some qualifications: > > - I use factories heavily (in this example Factory Girl) to make it easier to write tests. I don't worry about the slowness of using real model instances until the spec suite actually becomes large enough for it to be a problem. I also don't worry about the risk of cascading failures (broken model breaks controller spec) because I value the simplicity that comes with keeping mocking and stubbing to a minimum in the specs, and I am wary of the insulation that mocking and stubbing bring and can actually hide real failures (eg. API changes but spec keeps passing anyway). I still do mock and stub, but generally only where it is not easier to just verify state (and it often is easier). > > - I use RR for mocking because I like the syntax. Even in a state-based approach, you'll see I have to stub out the "current_user" method on the controller. > > - I use a "before" block that sets up @user, @params, and does the stubbing, so that I can reuse the same stuff in many different "it" blocks. > > - And I try to keep each "it" block as short as possible, just do the post then inspect the state afterwards. In this case the state that I am checking for is the externally visible stuff like what got assigned (assigns), what got rendered (render_template) or redirected (redirect_to), what flash or cookies got set, and so on. If need be, I can query the database. > > - And finally, note that this is written for Rails 3/RSpec 2, which I've been using solidly for the last month and have now forgotten what Rails 2/RSpec 1 specs looked like! > > So with all that said, this is more or less what my state-based approach would look like: > > before do > @user = User.make! > stub(controller).current_user { @user } > @params = { :post => { :title => 'foo', :body => 'bar' } } > end > > it 'should set created_by' do > post :create, @params > assigns[:post].created_by.should == @user > end > > ... > > The controller/action is treated as a "black box" which I never look inside. Each "it" block basically just follows this pattern: > > 1. Feed params into the black box > 2. Check _one_ piece of state afterwards > > By trying to keep only one "should" assertion in each "it" block I get nice granularity in the event of failure. > > It is not "better" nor "the right" way, it is just "a" way of doing it. I've also written controller specs where I ended up mocking left, right and center, but if I can take the state-based approach I generally prefer it. The app I'm currently working on has about 3,000 examples, and the suite runs fast enough that I don't yet feel the need to change my emphasis away from state-based testing. > I'm curious, Wincent, what you consider to be "fast enough"? You have about twice as many examples as I have in a project, and I'm starting to think that it's taking too long to run the whole suite. I do tons of mocking and stubbing (and grow very weary of it), but can't imagine how long my suite would take if I didn't. Currently, if I run with RCov, it's in the 6-7 minute range. Without RCov, it's between 5-6 depending on whether it's running in Ruby 1.8.7 or 1.9.1 (1.9.1 being faster). I am using PostgreSQL in testing, though, so I know that's adding a bit. I was using SQLite in testing until recently, and that was still up over 3-4 minutes. [I switched to PostgreSQL in testing so I could take advantage of PostgreSQL specific features. There is zero chance that this app will ever need to run on anything other than PG, so portability is not a concern.] There are a couple of tests that take quite a bit of time (one generates a PDF and verifies that it is where it is supposed to be and another creates a bunch of records to calculate statistics for), but even without them, the suite is taking over three minutes. So how long do your 3k examples take? Peace, Phillip From dchelimsky at gmail.com Fri Jul 9 23:38:10 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 9 Jul 2010 22:38:10 -0500 Subject: [rspec-users] Setting up rspec-rails for hacking In-Reply-To: References: <5917e287-1431-4f0a-86ee-e69f1dda0335@t10g2000yqg.googlegroups.com> Message-ID: <3F1BE504-06C0-495C-BFC7-BD523C0FF8FA@gmail.com> On Jul 9, 2010, at 8:06 AM, David Chelimsky wrote: > On Jul 9, 2010, at 6:59 AM, garren wrote: >> >> >> On Jul 7, 12:34 pm, David Chelimsky wrote: >>> On Jul 7, 2010, at 5:26 AM, Trevor Lalish-Menagh wrote: >>> >>>>> Did you know about the rspec-dev meta project? >>> >>>>> http://github.com/rspec/rspec-dev >>> >>>> That is great. I should have looked for that before setting this up. I just didn't think about it. >>> >>>>> Perhaps we should update the rspec-* READMEs with a point back to rspec-dev so that people know about it? >>> >>>> Good call. That would help. >>> >>> Done: >>> >>> http://github.com/rspec/rspechttp://github.com/rspec/rspec-corehttp://github.com/rspec/rspec-expectationshttp://github.com/rspec/rspec-mockshttp://github.com/rspec/rspec-rails >> >> I've followed the instructions to install the dev environment, when I >> run rake install I get this for the rspec-rails: >> cp ./templates/Gemfile ./tmp/example_app/ >> rake rails:template LOCATION='../../templates/generate_stuff.rb' >> (in /Users/garren/webdev/rspec-dev/repos/rspec-rails/tmp/example_app) >> generate rspec:install >> generate controller wombats index >> generate controller welcome index >> generate integration_test widgets >> generate mailer Notifications signup >> generate model thing name:string >> generate helper things >> generate scaffold widget name:string category:string >> instock:boolean >> generate observer widget >> generate scaffold gadget >> run rake db:migrate from "." >> run rake db:test:prepare from "." >> /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -I >> "/Library/Ruby/Gems/1.8/gems/cucumber-0.8.3/lib:lib" "/Library/Ruby/ >> Gems/1.8/gems/cucumber-0.8.3/bin/cucumber" --format progress >> Using the default profile... >> You have already activated rspec-expectations 2.0.0.beta.13, but your >> Gemfile requires rspec-expectations 2.0.0.beta.16. Consider using >> bundle exec. (Gem::LoadError) >> >> Any ideas on how to fix this? > > Looks like a change to aruba broke the rspec build :) Looking into it now. It wasn't aruba. I'm not 100% clear about all this, but I had added Bundler.setup in a couple of places where it wasn't necessary, and it caused trouble. It's now only in the Rakefiles in each repo and all appears to be well. Please give it a shot again and let me know how it's all working. Thx, David From win at wincent.com Sat Jul 10 06:21:01 2010 From: win at wincent.com (Wincent Colaiuta) Date: Sat, 10 Jul 2010 12:21:01 +0200 Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <4C37E920.5070203@gmail.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> <610AA529-9854-44F4-864E-AC92A562DF67@wincent.com> <4baee084-e4a5-460d-921d-cd7d714b2d13@r27g2000yqb.googlegroups.com> <4D5B4912-9620-4641-96E3-8ED928BF1F57@wincent.com> <4C37E920.5070203@gmail.com> Message-ID: El 10/07/2010, a las 05:29, Phillip Koebbe escribi?: >> It is not "better" nor "the right" way, it is just "a" way of doing it. I've also written controller specs where I ended up mocking left, right and center, but if I can take the state-based approach I generally prefer it. The app I'm currently working on has about 3,000 examples, and the suite runs fast enough that I don't yet feel the need to change my emphasis away from state-based testing. > > I'm curious, Wincent, what you consider to be "fast enough"? You have about twice as many examples as I have in a project, and I'm starting to think that it's taking too long to run the whole suite. I do tons of mocking and stubbing (and grow very weary of it), but can't imagine how long my suite would take if I didn't. Currently, if I run with RCov, it's in the 6-7 minute range. Without RCov, it's between 5-6 depending on whether it's running in Ruby 1.8.7 or 1.9.1 (1.9.1 being faster). I am using PostgreSQL in testing, though, so I know that's adding a bit. I was using SQLite in testing until recently, and that was still up over 3-4 minutes. [I switched to PostgreSQL in testing so I could take advantage of PostgreSQL specific features. There is zero chance that this app will ever need to run on anything other than PG, so portability is not a concern.] There are a couple of tests that take quite a bit of time (one generates a PDF and verifies that it is where it is supposed to be and another creates a bunch of records to calculate statistics for), but even without them, the suite is taking over three minutes. > > So how long do your 3k examples take? About 4 minutes for the entire thing, so, yes, the suite as a whole is far from providing "instant feedback". The vast majority of the examples, however, run very very fast. I'd say that 80% of the time is due to the slowest 20% of the specs. The turn-around time for individual specs (eg. change a model, run model specs; change a controller, run controller specs) is obviously quite fine. I think the biggest speed gain wouldn't be from doing more mocking and stubbing, but actually from swapping in an in-memory database instead of MySQL. Not sure how hard that would be, to be honest. (Wondering if it's possible to run get MySQL to run from a RAM disk, seeing as I unfortunately do have some MySQL-specific stuff in there that prevents me from swapping away from it for testing.) Slowest specs, of course, are the acceptance ones (running through Steak/Capybara/Culerity/Celerity). This app is quite an old one written before the days of Cucumber and Story Runner, so the acceptance coverage is way behind the rest of the specs. I expect that once I catch up on the acceptance side it will get much, much, much slower. I can see myself with 4 minute runs of the whole suite minus the acceptance specs, followed by 10 or 20 minute runs of the acceptance specs. Cheers, Wincent From win at wincent.com Sat Jul 10 10:05:31 2010 From: win at wincent.com (Wincent Colaiuta) Date: Sat, 10 Jul 2010 16:05:31 +0200 Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <683C8A86-BB84-45E7-B4A0-DA4DD922EFC6@wincent.com> <565e3e61-632d-41ad-8858-7a0dc6e9c56a@j4g2000yqh.googlegroups.com> <610AA529-9854-44F4-864E-AC92A562DF67@wincent.com> <4baee084-e4a5-460d-921d-cd7d714b2d13@r27g2000yqb.googlegroups.com> <4D5B4912-9620-4641-96E3-8ED928BF1F57@wincent.com> <4C37E920.5070203@gmail.com> Message-ID: <15BD64EF-D3C9-4EDD-BC44-2B668E5D5692@wincent.com> El 10/07/2010, a las 12:21, Wincent Colaiuta escribi?: > I think the biggest speed gain wouldn't be from doing more mocking and stubbing, but actually from swapping in an in-memory database instead of MySQL. Not sure how hard that would be, to be honest. (Wondering if it's possible to run get MySQL to run from a RAM disk, seeing as I unfortunately do have some MySQL-specific stuff in there that prevents me from swapping away from it for testing.) So I thought I'd try setting this up based on notes found here (nothing Rails specific here, post is written by a Django developer): http://kotega.com/blog/2010/apr/12/mysql-ramdisk-osx/ Alas, the before-and-after timings don't bring the kind of speed up I was hoping for: normal disk real 2m51.720s user 2m30.692s sys 0m2.653s ram disk real 2m42.268s user 2m31.590s sys 0m2.499s It's possible that one could get better performance by tuning some MySQL parameters, but I am sceptical about the gains being very impressive. Cheers, Wincent From daniel.amselem at gmail.com Sat Jul 10 14:26:55 2010 From: daniel.amselem at gmail.com (Daniel Salmeron Amselem) Date: Sat, 10 Jul 2010 11:26:55 -0700 (PDT) Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> Message-ID: <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> I've been doing some research on this problem, and I found this discussion on Lighthouse: https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil As it seems, this is not a problem with Rails 3 anymore, but how can I make it work for rails 2.3.8? On Jul 9, 2:45?pm, Daniel Salmeron Amselem wrote: > I've been trying to test a very simple action on a controller with > this setup: > > rspec 1.3.0 > ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] > Rails 2.3.8 > devise 1.0.8 > > And this is the test: > > ? ? before :each do > ? ? ? @member = Factory.create(:member) > ? ? ? sign_in @member > ? ? ? @person = Person.new > ? ? end > > ? ? it "should render form for a new person on GET people#new" do > ? ? ? current_member.should_receive(:build_person).and_return(@person) > > ? ? ? get :new > > ? ? ? assigns[:person].should == @person > ? ? ? response.should be_success > ? ? ? response.should render_template("new") > ? ? end > > This test creates a user, which is stored in the database with a > correct password. Running this test results in this error: > > 1) > NoMethodError in 'PeopleController Methods should render form for a > new person on GET people#new' > You have a nil object when you didn't expect it! > You might have expected an instance of ActiveRecord::Base. > The error occurred while evaluating nil.[]= > /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > session_serializer.rb:25:in `store' > /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > 73:in `sign_in' > /Users/damselem/Documents/project/spec/controllers/ > people_controller_spec.rb:15: > > Finished in 0.625754 seconds > > 23 examples, 1 failure > > I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > session_serializer.rb and I changed the file in order to print out > some values: > > ? ?def store(user, scope) > ? ? ? return unless user > ? ? ? p scope > ? ? ? p key_for(scope) > ? ? ? p user > ? ? ? p serialize(user) > ? ? ? p session > ? ? ? session[key_for(scope)] = serialize(user) > ? ? end > > When running the test again I get: > > :member > > "warden.user.member.key" > > Member id: 1, email: "member2 at hv_club.com", encrypted_password: > "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: > "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, > confirmation_sent_at: nil, reset_password_token: nil, remember_token: > nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: > nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: > nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 > 16:45:44" > > [Member(id: integer, email: string, encrypted_password: string, > password_salt: string, confirmation_token: string, confirmed_at: > datetime, confirmation_sent_at: datetime, reset_password_token: > string, remember_token: string, remember_created_at: datetime, > sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: > datetime, current_sign_in_ip: string, last_sign_in_ip: string, > created_at: datetime, updated_at: datetime), 1] > > nil > > So it seems session is not initialized. Any ideas on how to fix this? > BTW, I already contacted Jose Valim through GitHub and he recommended > me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 > > Thanks. > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Sat Jul 10 14:31:56 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 10 Jul 2010 13:31:56 -0500 Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> Message-ID: On Jul 10, 2010, at 1:26 PM, Daniel Salmeron Amselem wrote: > On Jul 9, 2:45 pm, Daniel Salmeron Amselem > wrote: >> I've been trying to test a very simple action on a controller with >> this setup: >> >> rspec 1.3.0 >> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] >> Rails 2.3.8 >> devise 1.0.8 >> >> And this is the test: >> >> before :each do >> @member = Factory.create(:member) >> sign_in @member >> @person = Person.new >> end >> >> it "should render form for a new person on GET people#new" do >> current_member.should_receive(:build_person).and_return(@person) >> >> get :new >> >> assigns[:person].should == @person >> response.should be_success >> response.should render_template("new") >> end >> >> This test creates a user, which is stored in the database with a >> correct password. Running this test results in this error: >> >> 1) >> NoMethodError in 'PeopleController Methods should render form for a >> new person on GET people#new' >> You have a nil object when you didn't expect it! >> You might have expected an instance of ActiveRecord::Base. >> The error occurred while evaluating nil.[]= >> /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ >> session_serializer.rb:25:in `store' >> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: >> 73:in `sign_in' >> /Users/damselem/Documents/project/spec/controllers/ >> people_controller_spec.rb:15: >> >> Finished in 0.625754 seconds >> >> 23 examples, 1 failure >> >> I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ >> session_serializer.rb and I changed the file in order to print out >> some values: >> >> def store(user, scope) >> return unless user >> p scope >> p key_for(scope) >> p user >> p serialize(user) >> p session >> session[key_for(scope)] = serialize(user) >> end >> >> When running the test again I get: >> >> :member >> >> "warden.user.member.key" >> >> Member id: 1, email: "member2 at hv_club.com", encrypted_password: >> "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: >> "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, >> confirmation_sent_at: nil, reset_password_token: nil, remember_token: >> nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: >> nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: >> nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 >> 16:45:44" >> >> [Member(id: integer, email: string, encrypted_password: string, >> password_salt: string, confirmation_token: string, confirmed_at: >> datetime, confirmation_sent_at: datetime, reset_password_token: >> string, remember_token: string, remember_created_at: datetime, >> sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: >> datetime, current_sign_in_ip: string, last_sign_in_ip: string, >> created_at: datetime, updated_at: datetime), 1] >> >> nil >> >> So it seems session is not initialized. Any ideas on how to fix this? >> BTW, I already contacted Jose Valim through GitHub and he recommended >> me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 >> >> Thanks. > I've been doing some research on this problem, and I found this > discussion on Lighthouse: https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil > > As it seems, this is not a problem with Rails 3 anymore, but how can I > make it work for rails 2.3.8? We've got this in an app using devise with rails 2.3.5 - should work with 2.3.8. before do request.env['warden'].stub(:authenticate!) { double(User) } end HTH, David From daniel.amselem at gmail.com Sat Jul 10 15:45:01 2010 From: daniel.amselem at gmail.com (Daniel Salmeron Amselem) Date: Sat, 10 Jul 2010 12:45:01 -0700 (PDT) Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> Message-ID: <64ef3984-22b5-4af6-b73c-a022ad698df5@a30g2000yqn.googlegroups.com> Thanks David, but could you explain me how should I use this before do block in order to sign in an user? I am not a very experienced Rails developer and I tried different things like: 13 before :each do 14 # @member = Factory.create(:member) 15 request.env['warden'].stub(:authenticate!) { double(Member) } 16 sign_in @member 17 @person = Person.new 18 end which throws this error: RuntimeError in 'PeopleController Methods should render form for a new person on GET people#new' Could not find a valid mapping for /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/mapping.rb:49:in `find_scope!' /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: 71:in `sign_in' /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ people_controller_spec.rb:16: Finished in 0.437813 seconds 23 examples, 1 failure Thanks David, and sorry for asking too much about this issue. On Jul 10, 2:31?pm, David Chelimsky wrote: > On Jul 10, 2010, at 1:26 PM, Daniel Salmeron Amselem wrote: > > > > > > > On Jul 9, 2:45 pm, Daniel Salmeron Amselem > > wrote: > >> I've been trying to test a very simple action on a controller with > >> this setup: > > >> rspec 1.3.0 > >> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] > >> Rails 2.3.8 > >> devise 1.0.8 > > >> And this is the test: > > >> ? ? before :each do > >> ? ? ? @member = Factory.create(:member) > >> ? ? ? sign_in @member > >> ? ? ? @person = Person.new > >> ? ? end > > >> ? ? it "should render form for a new person on GET people#new" do > >> ? ? ? current_member.should_receive(:build_person).and_return(@person) > > >> ? ? ? get :new > > >> ? ? ? assigns[:person].should == @person > >> ? ? ? response.should be_success > >> ? ? ? response.should render_template("new") > >> ? ? end > > >> This test creates a user, which is stored in the database with a > >> correct password. Running this test results in this error: > > >> 1) > >> NoMethodError in 'PeopleController Methods should render form for a > >> new person on GET people#new' > >> You have a nil object when you didn't expect it! > >> You might have expected an instance of ActiveRecord::Base. > >> The error occurred while evaluating nil.[]= > >> /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > >> session_serializer.rb:25:in `store' > >> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > >> 73:in `sign_in' > >> /Users/damselem/Documents/project/spec/controllers/ > >> people_controller_spec.rb:15: > > >> Finished in 0.625754 seconds > > >> 23 examples, 1 failure > > >> I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > >> session_serializer.rb and I changed the file in order to print out > >> some values: > > >> ? ?def store(user, scope) > >> ? ? ? return unless user > >> ? ? ? p scope > >> ? ? ? p key_for(scope) > >> ? ? ? p user > >> ? ? ? p serialize(user) > >> ? ? ? p session > >> ? ? ? session[key_for(scope)] = serialize(user) > >> ? ? end > > >> When running the test again I get: > > >> :member > > >> "warden.user.member.key" > > >> Member id: 1, email: "member2 at hv_club.com", encrypted_password: > >> "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: > >> "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, > >> confirmation_sent_at: nil, reset_password_token: nil, remember_token: > >> nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: > >> nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: > >> nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 > >> 16:45:44" > > >> [Member(id: integer, email: string, encrypted_password: string, > >> password_salt: string, confirmation_token: string, confirmed_at: > >> datetime, confirmation_sent_at: datetime, reset_password_token: > >> string, remember_token: string, remember_created_at: datetime, > >> sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: > >> datetime, current_sign_in_ip: string, last_sign_in_ip: string, > >> created_at: datetime, updated_at: datetime), 1] > > >> nil > > >> So it seems session is not initialized. Any ideas on how to fix this? > >> BTW, I already contacted Jose Valim through GitHub and he recommended > >> me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 > > >> Thanks. > > I've been doing some research on this problem, and I found this > > discussion on Lighthouse:https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil > > > As it seems, this is not a problem with Rails 3 anymore, but how can I > > make it work for rails 2.3.8? > > We've got this in an app using devise with rails 2.3.5 - should work with 2.3.8. > > ? ? before do > ? ? ? request.env['warden'].stub(:authenticate!) { double(User) } > ? ? end > > HTH, > David > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Sat Jul 10 15:53:16 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 10 Jul 2010 14:53:16 -0500 Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: <64ef3984-22b5-4af6-b73c-a022ad698df5@a30g2000yqn.googlegroups.com> References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> <64ef3984-22b5-4af6-b73c-a022ad698df5@a30g2000yqn.googlegroups.com> Message-ID: On Jul 10, 2010, at 2:45 PM, Daniel Salmeron Amselem wrote: > > On Jul 10, 2:31 pm, David Chelimsky wrote: >> On Jul 10, 2010, at 1:26 PM, Daniel Salmeron Amselem wrote: >> >> >> >> >> >>> On Jul 9, 2:45 pm, Daniel Salmeron Amselem >>> wrote: >>>> I've been trying to test a very simple action on a controller with >>>> this setup: >> >>>> rspec 1.3.0 >>>> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] >>>> Rails 2.3.8 >>>> devise 1.0.8 >> >>>> And this is the test: >> >>>> before :each do >>>> @member = Factory.create(:member) >>>> sign_in @member >>>> @person = Person.new >>>> end >> >>>> it "should render form for a new person on GET people#new" do >>>> current_member.should_receive(:build_person).and_return(@person) >> >>>> get :new >> >>>> assigns[:person].should == @person >>>> response.should be_success >>>> response.should render_template("new") >>>> end >> >>>> This test creates a user, which is stored in the database with a >>>> correct password. Running this test results in this error: >> >>>> 1) >>>> NoMethodError in 'PeopleController Methods should render form for a >>>> new person on GET people#new' >>>> You have a nil object when you didn't expect it! >>>> You might have expected an instance of ActiveRecord::Base. >>>> The error occurred while evaluating nil.[]= >>>> /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ >>>> session_serializer.rb:25:in `store' >>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: >>>> 73:in `sign_in' >>>> /Users/damselem/Documents/project/spec/controllers/ >>>> people_controller_spec.rb:15: >> >>>> Finished in 0.625754 seconds >> >>>> 23 examples, 1 failure >> >>>> I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ >>>> session_serializer.rb and I changed the file in order to print out >>>> some values: >> >>>> def store(user, scope) >>>> return unless user >>>> p scope >>>> p key_for(scope) >>>> p user >>>> p serialize(user) >>>> p session >>>> session[key_for(scope)] = serialize(user) >>>> end >> >>>> When running the test again I get: >> >>>> :member >> >>>> "warden.user.member.key" >> >>>> Member id: 1, email: "member2 at hv_club.com", encrypted_password: >>>> "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: >>>> "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, >>>> confirmation_sent_at: nil, reset_password_token: nil, remember_token: >>>> nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: >>>> nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: >>>> nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 >>>> 16:45:44" >> >>>> [Member(id: integer, email: string, encrypted_password: string, >>>> password_salt: string, confirmation_token: string, confirmed_at: >>>> datetime, confirmation_sent_at: datetime, reset_password_token: >>>> string, remember_token: string, remember_created_at: datetime, >>>> sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: >>>> datetime, current_sign_in_ip: string, last_sign_in_ip: string, >>>> created_at: datetime, updated_at: datetime), 1] >> >>>> nil >> >>>> So it seems session is not initialized. Any ideas on how to fix this? >>>> BTW, I already contacted Jose Valim through GitHub and he recommended >>>> me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 >> >>>> Thanks. >>> I've been doing some research on this problem, and I found this >>> discussion on Lighthouse:https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil >> >>> As it seems, this is not a problem with Rails 3 anymore, but how can I >>> make it work for rails 2.3.8? >> >> We've got this in an app using devise with rails 2.3.5 - should work with 2.3.8. >> >> before do >> request.env['warden'].stub(:authenticate!) { double(User) } >> end >> >> HTH, >> David > Thanks David, but could you explain me how should I use this before do > block in order to sign in an user? That's all that's in the before. It effectively signs in the user. If you have a specific user you want to use, you can do user = Factory(:user) request.env['warden'].stub(:authenticate!) { user } > I am not a very experienced Rails > developer and I tried different things like: > > 13 before :each do > 14 # @member = Factory.create(:member) > 15 request.env['warden'].stub(:authenticate!) { double(Member) } > 16 sign_in @member > 17 @person = Person.new > 18 end > > which throws this error: > > RuntimeError in 'PeopleController Methods should render form for a new > person on GET people#new' > Could not find a valid mapping for > /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/mapping.rb:49:in > `find_scope!' > /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > 71:in `sign_in' > /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ > people_controller_spec.rb:16: > > Finished in 0.437813 seconds > > 23 examples, 1 failure > > Thanks David, and sorry for asking too much about this issue. From dchelimsky at gmail.com Sat Jul 10 15:54:12 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 10 Jul 2010 14:54:12 -0500 Subject: [rspec-users] [Rails] Stubbed static methods are bleeding over into other specs and making them fail In-Reply-To: References: <2F30C790-F219-4DD4-8932-8238E66C752D@gmail.com> Message-ID: <29F1F5F4-9E70-4F0E-8D2E-8E04E510D957@gmail.com> On Jul 9, 2010, at 7:37 PM, Patrick Gannon wrote: > > On Mon, Jul 5, 2010 at 1:26 PM, David Chelimsky wrote: > I just pushed what I believe to be a fix for this - please try pointing Gemfile to the git repos again. It should work if you do this with all of them: > > gem "rspec-rails", :git => "git://github.com/rspec/rspec-rails.git" > gem "rspec", :git => "git://github.com/rspec/rspec.git" > gem "rspec-core", :git => "git://github.com/rspec/rspec-core.git" > gem "rspec-expectations", :git => "git://github.com/rspec/rspec-expectations.git" > gem "rspec-mocks", :git => "git://github.com/rspec/rspec-mocks.git" > > Let me know if it works out. > > > Hi David, > > I just got a chance to try this, and ran into more problems. Prior to trying this, we were running RSpec2 beta 13. When I changed our Gemfile to depend on 'edge' RSpec et al (as you suggested above), I get a very strange error when I run rake (after doing a 'bundle install'). The same error occurs after I tell it specifically to use beta 16 (rather than 'edge'). It seems to somehow not be able to find the bundler gem when it runs the main bundler script from within rake: > > C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:779:in `report_activate_error': Could not find RubyGem bundler (>= 0) (Gem::LoadError) > from C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:214:in `activate' > from C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:1082:in `gem' > from C:/Ruby187/bin/bundle:18 > rake aborted! > bundle exec C:/Ruby187/bin/ruby.exe -Ilib -Ispec "./spec/controllers/discrepancies_controller_spec.rb" (...spec names omitted..) failed > > When I downgrade back to beta 13, everything works again. I can't seem to figure out why it wouldn't be able to find the bundler gem (since obviously bundler is installed), so I cannot say whether or not your fix for the stubbing issue solved my problem. The stack trace (resulting from running rake with "--trace") and my current list of installed gems (via "bundle list") is here: http://gist.github.com/470278 (sorry for the line breaks) bundler-1.0.0.beta.4 should fix this. Please give it a shot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From daniel.amselem at gmail.com Sat Jul 10 16:21:43 2010 From: daniel.amselem at gmail.com (Daniel Salmeron Amselem) Date: Sat, 10 Jul 2010 13:21:43 -0700 (PDT) Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> <64ef3984-22b5-4af6-b73c-a022ad698df5@a30g2000yqn.googlegroups.com> Message-ID: Oh, I tried that too, but then current_member doesn't work.... 1) NameError in 'PeopleController Methods should render form for a new person on GET people#new' undefined local variable or method `current_member' for # /Library/Ruby/Gems/1.8/gems/actionpack-2.3.8/lib/action_controller/ test_process.rb:511:in `method_missing' /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ people_controller_spec.rb:21: Finished in 0.543299 seconds 23 examples, 1 failure which it seems to be available when using devise: http://github.com/plataformatec/devise/tree/v1.0.8 . Any idea? On Jul 10, 3:53?pm, David Chelimsky wrote: > On Jul 10, 2010, at 2:45 PM, Daniel Salmeron Amselem wrote: > > > > > > > > > On Jul 10, 2:31 pm, David Chelimsky wrote: > >> On Jul 10, 2010, at 1:26 PM, Daniel Salmeron Amselem wrote: > > >>> On Jul 9, 2:45 pm, Daniel Salmeron Amselem > >>> wrote: > >>>> I've been trying to test a very simple action on a controller with > >>>> this setup: > > >>>> rspec 1.3.0 > >>>> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] > >>>> Rails 2.3.8 > >>>> devise 1.0.8 > > >>>> And this is the test: > > >>>> ? ? before :each do > >>>> ? ? ? @member = Factory.create(:member) > >>>> ? ? ? sign_in @member > >>>> ? ? ? @person = Person.new > >>>> ? ? end > > >>>> ? ? it "should render form for a new person on GET people#new" do > >>>> ? ? ? current_member.should_receive(:build_person).and_return(@person) > > >>>> ? ? ? get :new > > >>>> ? ? ? assigns[:person].should == @person > >>>> ? ? ? response.should be_success > >>>> ? ? ? response.should render_template("new") > >>>> ? ? end > > >>>> This test creates a user, which is stored in the database with a > >>>> correct password. Running this test results in this error: > > >>>> 1) > >>>> NoMethodError in 'PeopleController Methods should render form for a > >>>> new person on GET people#new' > >>>> You have a nil object when you didn't expect it! > >>>> You might have expected an instance of ActiveRecord::Base. > >>>> The error occurred while evaluating nil.[]= > >>>> /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > >>>> session_serializer.rb:25:in `store' > >>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > >>>> 73:in `sign_in' > >>>> /Users/damselem/Documents/project/spec/controllers/ > >>>> people_controller_spec.rb:15: > > >>>> Finished in 0.625754 seconds > > >>>> 23 examples, 1 failure > > >>>> I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > >>>> session_serializer.rb and I changed the file in order to print out > >>>> some values: > > >>>> ? ?def store(user, scope) > >>>> ? ? ? return unless user > >>>> ? ? ? p scope > >>>> ? ? ? p key_for(scope) > >>>> ? ? ? p user > >>>> ? ? ? p serialize(user) > >>>> ? ? ? p session > >>>> ? ? ? session[key_for(scope)] = serialize(user) > >>>> ? ? end > > >>>> When running the test again I get: > > >>>> :member > > >>>> "warden.user.member.key" > > >>>> Member id: 1, email: "member2 at hv_club.com", encrypted_password: > >>>> "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: > >>>> "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, > >>>> confirmation_sent_at: nil, reset_password_token: nil, remember_token: > >>>> nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: > >>>> nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: > >>>> nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 > >>>> 16:45:44" > > >>>> [Member(id: integer, email: string, encrypted_password: string, > >>>> password_salt: string, confirmation_token: string, confirmed_at: > >>>> datetime, confirmation_sent_at: datetime, reset_password_token: > >>>> string, remember_token: string, remember_created_at: datetime, > >>>> sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: > >>>> datetime, current_sign_in_ip: string, last_sign_in_ip: string, > >>>> created_at: datetime, updated_at: datetime), 1] > > >>>> nil > > >>>> So it seems session is not initialized. Any ideas on how to fix this? > >>>> BTW, I already contacted Jose Valim through GitHub and he recommended > >>>> me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 > > >>>> Thanks. > >>> I've been doing some research on this problem, and I found this > >>> discussion on Lighthouse:https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil > > >>> As it seems, this is not a problem with Rails 3 anymore, but how can I > >>> make it work for rails 2.3.8? > > >> We've got this in an app using devise with rails 2.3.5 - should work with 2.3.8. > > >> ? ? before do > >> ? ? ? request.env['warden'].stub(:authenticate!) { double(User) } > >> ? ? end > > >> HTH, > >> David > > Thanks David, but could you explain me how should I use this before do > > block in order to sign in an user? > > That's all that's in the before. It effectively signs in the user. If you have a specific user you want to use, you can do > > user = Factory(:user) > ? request.env['warden'].stub(:authenticate!) { user } > > > > > > > I am not a very experienced Rails > > developer and I tried different things like: > > > 13 ? ?before :each do > > 14 ? ? ?# @member = Factory.create(:member) > > 15 ? ? ?request.env['warden'].stub(:authenticate!) { double(Member) } > > 16 ? ? ?sign_in @member > > 17 ? ? ?@person = Person.new > > 18 ? ?end > > > which throws this error: > > > RuntimeError in 'PeopleController Methods should render form for a new > > person on GET people#new' > > Could not find a valid mapping for > > /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/mapping.rb:49:in > > `find_scope!' > > /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > > 71:in `sign_in' > > /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ > > people_controller_spec.rb:16: > > > Finished in 0.437813 seconds > > > 23 examples, 1 failure > > > Thanks David, and sorry for asking too much about this issue. > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Sat Jul 10 16:32:11 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 10 Jul 2010 15:32:11 -0500 Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> <64ef3984-22b5-4af6-b73c-a022ad698df5@a30g2000yqn.googlegroups.com> Message-ID: On Jul 10, 2010, at 3:21 PM, Daniel Salmeron Amselem wrote: > On Jul 10, 3:53 pm, David Chelimsky wrote: >> On Jul 10, 2010, at 2:45 PM, Daniel Salmeron Amselem wrote: >>> On Jul 10, 2:31 pm, David Chelimsky wrote: >>>> On Jul 10, 2010, at 1:26 PM, Daniel Salmeron Amselem wrote: >> >>>>> On Jul 9, 2:45 pm, Daniel Salmeron Amselem >>>>> wrote: >>>>>> I've been trying to test a very simple action on a controller with >>>>>> this setup: >> >>>>>> rspec 1.3.0 >>>>>> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] >>>>>> Rails 2.3.8 >>>>>> devise 1.0.8 >> >>>>>> And this is the test: >> >>>>>> before :each do >>>>>> @member = Factory.create(:member) >>>>>> sign_in @member >>>>>> @person = Person.new >>>>>> end >> >>>>>> it "should render form for a new person on GET people#new" do >>>>>> current_member.should_receive(:build_person).and_return(@person) >> >>>>>> get :new >> >>>>>> assigns[:person].should == @person >>>>>> response.should be_success >>>>>> response.should render_template("new") >>>>>> end >> >>>>>> This test creates a user, which is stored in the database with a >>>>>> correct password. Running this test results in this error: >> >>>>>> 1) >>>>>> NoMethodError in 'PeopleController Methods should render form for a >>>>>> new person on GET people#new' >>>>>> You have a nil object when you didn't expect it! >>>>>> You might have expected an instance of ActiveRecord::Base. >>>>>> The error occurred while evaluating nil.[]= >>>>>> /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ >>>>>> session_serializer.rb:25:in `store' >>>>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: >>>>>> 73:in `sign_in' >>>>>> /Users/damselem/Documents/project/spec/controllers/ >>>>>> people_controller_spec.rb:15: >> >>>>>> Finished in 0.625754 seconds >> >>>>>> 23 examples, 1 failure >> >>>>>> I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ >>>>>> session_serializer.rb and I changed the file in order to print out >>>>>> some values: >> >>>>>> def store(user, scope) >>>>>> return unless user >>>>>> p scope >>>>>> p key_for(scope) >>>>>> p user >>>>>> p serialize(user) >>>>>> p session >>>>>> session[key_for(scope)] = serialize(user) >>>>>> end >> >>>>>> When running the test again I get: >> >>>>>> :member >> >>>>>> "warden.user.member.key" >> >>>>>> Member id: 1, email: "member2 at hv_club.com", encrypted_password: >>>>>> "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: >>>>>> "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, >>>>>> confirmation_sent_at: nil, reset_password_token: nil, remember_token: >>>>>> nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: >>>>>> nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: >>>>>> nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 >>>>>> 16:45:44" >> >>>>>> [Member(id: integer, email: string, encrypted_password: string, >>>>>> password_salt: string, confirmation_token: string, confirmed_at: >>>>>> datetime, confirmation_sent_at: datetime, reset_password_token: >>>>>> string, remember_token: string, remember_created_at: datetime, >>>>>> sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: >>>>>> datetime, current_sign_in_ip: string, last_sign_in_ip: string, >>>>>> created_at: datetime, updated_at: datetime), 1] >> >>>>>> nil >> >>>>>> So it seems session is not initialized. Any ideas on how to fix this? >>>>>> BTW, I already contacted Jose Valim through GitHub and he recommended >>>>>> me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 >> >>>>>> Thanks. >>>>> I've been doing some research on this problem, and I found this >>>>> discussion on Lighthouse:https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil >> >>>>> As it seems, this is not a problem with Rails 3 anymore, but how can I >>>>> make it work for rails 2.3.8? >> >>>> We've got this in an app using devise with rails 2.3.5 - should work with 2.3.8. >> >>>> before do >>>> request.env['warden'].stub(:authenticate!) { double(User) } >>>> end >> >>>> HTH, >>>> David >>> Thanks David, but could you explain me how should I use this before do >>> block in order to sign in an user? >> >> That's all that's in the before. It effectively signs in the user. If you have a specific user you want to use, you can do >> >> user = Factory(:user) >> request.env['warden'].stub(:authenticate!) { user } > Oh, I tried that too, but then current_member doesn't work.... > > 1) > NameError in 'PeopleController Methods should render form for a new > person on GET people#new' > undefined local variable or method `current_member' for > # This error is on the example itself, not the application code. Is there a reference to current_member in the spec itself? > /Library/Ruby/Gems/1.8/gems/actionpack-2.3.8/lib/action_controller/ > test_process.rb:511:in `method_missing' > /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ > people_controller_spec.rb:21: > > Finished in 0.543299 seconds > > 23 examples, 1 failure > > which it seems to be available when using devise: > http://github.com/plataformatec/devise/tree/v1.0.8 . Any idea? >>> I am not a very experienced Rails >>> developer and I tried different things like: >> >>> 13 before :each do >>> 14 # @member = Factory.create(:member) >>> 15 request.env['warden'].stub(:authenticate!) { double(Member) } >>> 16 sign_in @member >>> 17 @person = Person.new >>> 18 end >> >>> which throws this error: >> >>> RuntimeError in 'PeopleController Methods should render form for a new >>> person on GET people#new' >>> Could not find a valid mapping for >>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/mapping.rb:49:in >>> `find_scope!' >>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: >>> 71:in `sign_in' >>> /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ >>> people_controller_spec.rb:16: >> >>> Finished in 0.437813 seconds >> >>> 23 examples, 1 failure >> >>> Thanks David, and sorry for asking too much about this issue. >> >> _______________________________________________ >> rspec-users mailing list >> rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From daniel.amselem at gmail.com Sat Jul 10 16:38:55 2010 From: daniel.amselem at gmail.com (Daniel Salmeron Amselem) Date: Sat, 10 Jul 2010 13:38:55 -0700 (PDT) Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> <64ef3984-22b5-4af6-b73c-a022ad698df5@a30g2000yqn.googlegroups.com> Message-ID: <51328b4b-26db-410a-92e1-2318446251aa@j4g2000yqh.googlegroups.com> You're right David, my fault. Than you very much for all your help. On Jul 10, 4:32?pm, David Chelimsky wrote: > On Jul 10, 2010, at 3:21 PM, Daniel Salmeron Amselem wrote: > > > > > > > On Jul 10, 3:53 pm, David Chelimsky wrote: > >> On Jul 10, 2010, at 2:45 PM, Daniel Salmeron Amselem wrote: > >>> On Jul 10, 2:31 pm, David Chelimsky wrote: > >>>> On Jul 10, 2010, at 1:26 PM, Daniel Salmeron Amselem wrote: > > >>>>> On Jul 9, 2:45 pm, Daniel Salmeron Amselem > >>>>> wrote: > >>>>>> I've been trying to test a very simple action on a controller with > >>>>>> this setup: > > >>>>>> rspec 1.3.0 > >>>>>> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] > >>>>>> Rails 2.3.8 > >>>>>> devise 1.0.8 > > >>>>>> And this is the test: > > >>>>>> ? ? before :each do > >>>>>> ? ? ? @member = Factory.create(:member) > >>>>>> ? ? ? sign_in @member > >>>>>> ? ? ? @person = Person.new > >>>>>> ? ? end > > >>>>>> ? ? it "should render form for a new person on GET people#new" do > >>>>>> ? ? ? current_member.should_receive(:build_person).and_return(@person) > > >>>>>> ? ? ? get :new > > >>>>>> ? ? ? assigns[:person].should == @person > >>>>>> ? ? ? response.should be_success > >>>>>> ? ? ? response.should render_template("new") > >>>>>> ? ? end > > >>>>>> This test creates a user, which is stored in the database with a > >>>>>> correct password. Running this test results in this error: > > >>>>>> 1) > >>>>>> NoMethodError in 'PeopleController Methods should render form for a > >>>>>> new person on GET people#new' > >>>>>> You have a nil object when you didn't expect it! > >>>>>> You might have expected an instance of ActiveRecord::Base. > >>>>>> The error occurred while evaluating nil.[]= > >>>>>> /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > >>>>>> session_serializer.rb:25:in `store' > >>>>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > >>>>>> 73:in `sign_in' > >>>>>> /Users/damselem/Documents/project/spec/controllers/ > >>>>>> people_controller_spec.rb:15: > > >>>>>> Finished in 0.625754 seconds > > >>>>>> 23 examples, 1 failure > > >>>>>> I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > >>>>>> session_serializer.rb and I changed the file in order to print out > >>>>>> some values: > > >>>>>> ? ?def store(user, scope) > >>>>>> ? ? ? return unless user > >>>>>> ? ? ? p scope > >>>>>> ? ? ? p key_for(scope) > >>>>>> ? ? ? p user > >>>>>> ? ? ? p serialize(user) > >>>>>> ? ? ? p session > >>>>>> ? ? ? session[key_for(scope)] = serialize(user) > >>>>>> ? ? end > > >>>>>> When running the test again I get: > > >>>>>> :member > > >>>>>> "warden.user.member.key" > > >>>>>> Member id: 1, email: "member2 at hv_club.com", encrypted_password: > >>>>>> "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: > >>>>>> "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, > >>>>>> confirmation_sent_at: nil, reset_password_token: nil, remember_token: > >>>>>> nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: > >>>>>> nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: > >>>>>> nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 > >>>>>> 16:45:44" > > >>>>>> [Member(id: integer, email: string, encrypted_password: string, > >>>>>> password_salt: string, confirmation_token: string, confirmed_at: > >>>>>> datetime, confirmation_sent_at: datetime, reset_password_token: > >>>>>> string, remember_token: string, remember_created_at: datetime, > >>>>>> sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: > >>>>>> datetime, current_sign_in_ip: string, last_sign_in_ip: string, > >>>>>> created_at: datetime, updated_at: datetime), 1] > > >>>>>> nil > > >>>>>> So it seems session is not initialized. Any ideas on how to fix this? > >>>>>> BTW, I already contacted Jose Valim through GitHub and he recommended > >>>>>> me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 > > >>>>>> Thanks. > >>>>> I've been doing some research on this problem, and I found this > >>>>> discussion on Lighthouse:https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil > > >>>>> As it seems, this is not a problem with Rails 3 anymore, but how can I > >>>>> make it work for rails 2.3.8? > > >>>> We've got this in an app using devise with rails 2.3.5 - should work with 2.3.8. > > >>>> ? ? before do > >>>> ? ? ? request.env['warden'].stub(:authenticate!) { double(User) } > >>>> ? ? end > > >>>> HTH, > >>>> David > >>> Thanks David, but could you explain me how should I use this before do > >>> block in order to sign in an user? > > >> That's all that's in the before. It effectively signs in the user. If you have a specific user you want to use, you can do > > >> user = Factory(:user) > >> ? request.env['warden'].stub(:authenticate!) { user } > > Oh, I tried that too, but then current_member doesn't work.... > > > 1) > > NameError in 'PeopleController Methods should render form for a new > > person on GET people#new' > > undefined local variable or method `current_member' for > > # > > This error is on the example itself, not the application code. Is there a reference to current_member in the spec itself? > > > > > > > /Library/Ruby/Gems/1.8/gems/actionpack-2.3.8/lib/action_controller/ > > test_process.rb:511:in `method_missing' > > /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ > > people_controller_spec.rb:21: > > > Finished in 0.543299 seconds > > > 23 examples, 1 failure > > > which it seems to be available when using devise: > >http://github.com/plataformatec/devise/tree/v1.0.8. Any idea? > >>> I am not a very experienced Rails > >>> developer and I tried different things like: > > >>> 13 ? ?before :each do > >>> 14 ? ? ?# @member = Factory.create(:member) > >>> 15 ? ? ?request.env['warden'].stub(:authenticate!) { double(Member) } > >>> 16 ? ? ?sign_in @member > >>> 17 ? ? ?@person = Person.new > >>> 18 ? ?end > > >>> which throws this error: > > >>> RuntimeError in 'PeopleController Methods should render form for a new > >>> person on GET people#new' > >>> Could not find a valid mapping for > >>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/mapping.rb:49:in > >>> `find_scope!' > >>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > >>> 71:in `sign_in' > >>> /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ > >>> people_controller_spec.rb:16: > > >>> Finished in 0.437813 seconds > > >>> 23 examples, 1 failure > > >>> Thanks David, and sorry for asking too much about this issue. > > >> _______________________________________________ > >> rspec-users mailing list > >> rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > > rspec-users mailing list > > rspec-us... at rubyforge.org > >http://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Sat Jul 10 16:47:09 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 10 Jul 2010 15:47:09 -0500 Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: <51328b4b-26db-410a-92e1-2318446251aa@j4g2000yqh.googlegroups.com> References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> <64ef3984-22b5-4af6-b73c-a022ad698df5@a30g2000yqn.googlegroups.com> <51328b4b-26db-410a-92e1-2318446251aa@j4g2000yqh.googlegroups.com> Message-ID: <889ACF8E-998F-4EFD-9A40-9653F45B7639@gmail.com> On Jul 10, 2010, at 3:38 PM, Daniel Salmeron Amselem wrote: > You're right David, my fault. Than you very much for all your help. You got it working then? > On Jul 10, 4:32 pm, David Chelimsky wrote: >> On Jul 10, 2010, at 3:21 PM, Daniel Salmeron Amselem wrote: >>> On Jul 10, 3:53 pm, David Chelimsky wrote: >>>> On Jul 10, 2010, at 2:45 PM, Daniel Salmeron Amselem wrote: >>>>> On Jul 10, 2:31 pm, David Chelimsky wrote: >>>>>> On Jul 10, 2010, at 1:26 PM, Daniel Salmeron Amselem wrote: >> >>>>>>> On Jul 9, 2:45 pm, Daniel Salmeron Amselem >>>>>>> wrote: >>>>>>>> I've been trying to test a very simple action on a controller with >>>>>>>> this setup: >> >>>>>>>> rspec 1.3.0 >>>>>>>> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] >>>>>>>> Rails 2.3.8 >>>>>>>> devise 1.0.8 >> >>>>>>>> And this is the test: >> >>>>>>>> before :each do >>>>>>>> @member = Factory.create(:member) >>>>>>>> sign_in @member >>>>>>>> @person = Person.new >>>>>>>> end >> >>>>>>>> it "should render form for a new person on GET people#new" do >>>>>>>> current_member.should_receive(:build_person).and_return(@person) >> >>>>>>>> get :new >> >>>>>>>> assigns[:person].should == @person >>>>>>>> response.should be_success >>>>>>>> response.should render_template("new") >>>>>>>> end >> >>>>>>>> This test creates a user, which is stored in the database with a >>>>>>>> correct password. Running this test results in this error: >> >>>>>>>> 1) >>>>>>>> NoMethodError in 'PeopleController Methods should render form for a >>>>>>>> new person on GET people#new' >>>>>>>> You have a nil object when you didn't expect it! >>>>>>>> You might have expected an instance of ActiveRecord::Base. >>>>>>>> The error occurred while evaluating nil.[]= >>>>>>>> /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ >>>>>>>> session_serializer.rb:25:in `store' >>>>>>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: >>>>>>>> 73:in `sign_in' >>>>>>>> /Users/damselem/Documents/project/spec/controllers/ >>>>>>>> people_controller_spec.rb:15: >> >>>>>>>> Finished in 0.625754 seconds >> >>>>>>>> 23 examples, 1 failure >> >>>>>>>> I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ >>>>>>>> session_serializer.rb and I changed the file in order to print out >>>>>>>> some values: >> >>>>>>>> def store(user, scope) >>>>>>>> return unless user >>>>>>>> p scope >>>>>>>> p key_for(scope) >>>>>>>> p user >>>>>>>> p serialize(user) >>>>>>>> p session >>>>>>>> session[key_for(scope)] = serialize(user) >>>>>>>> end >> >>>>>>>> When running the test again I get: >> >>>>>>>> :member >> >>>>>>>> "warden.user.member.key" >> >>>>>>>> Member id: 1, email: "member2 at hv_club.com", encrypted_password: >>>>>>>> "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: >>>>>>>> "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, >>>>>>>> confirmation_sent_at: nil, reset_password_token: nil, remember_token: >>>>>>>> nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: >>>>>>>> nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: >>>>>>>> nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 >>>>>>>> 16:45:44" >> >>>>>>>> [Member(id: integer, email: string, encrypted_password: string, >>>>>>>> password_salt: string, confirmation_token: string, confirmed_at: >>>>>>>> datetime, confirmation_sent_at: datetime, reset_password_token: >>>>>>>> string, remember_token: string, remember_created_at: datetime, >>>>>>>> sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: >>>>>>>> datetime, current_sign_in_ip: string, last_sign_in_ip: string, >>>>>>>> created_at: datetime, updated_at: datetime), 1] >> >>>>>>>> nil >> >>>>>>>> So it seems session is not initialized. Any ideas on how to fix this? >>>>>>>> BTW, I already contacted Jose Valim through GitHub and he recommended >>>>>>>> me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 >> >>>>>>>> Thanks. >>>>>>> I've been doing some research on this problem, and I found this >>>>>>> discussion on Lighthouse:https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil >> >>>>>>> As it seems, this is not a problem with Rails 3 anymore, but how can I >>>>>>> make it work for rails 2.3.8? >> >>>>>> We've got this in an app using devise with rails 2.3.5 - should work with 2.3.8. >> >>>>>> before do >>>>>> request.env['warden'].stub(:authenticate!) { double(User) } >>>>>> end >> >>>>>> HTH, >>>>>> David >>>>> Thanks David, but could you explain me how should I use this before do >>>>> block in order to sign in an user? >> >>>> That's all that's in the before. It effectively signs in the user. If you have a specific user you want to use, you can do >> >>>> user = Factory(:user) >>>> request.env['warden'].stub(:authenticate!) { user } >>> Oh, I tried that too, but then current_member doesn't work.... >> >>> 1) >>> NameError in 'PeopleController Methods should render form for a new >>> person on GET people#new' >>> undefined local variable or method `current_member' for >>> # >> >> This error is on the example itself, not the application code. Is there a reference to current_member in the spec itself? >> >> >> >> >> >>> /Library/Ruby/Gems/1.8/gems/actionpack-2.3.8/lib/action_controller/ >>> test_process.rb:511:in `method_missing' >>> /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ >>> people_controller_spec.rb:21: >> >>> Finished in 0.543299 seconds >> >>> 23 examples, 1 failure >> >>> which it seems to be available when using devise: >>> http://github.com/plataformatec/devise/tree/v1.0.8. Any idea? >>>>> I am not a very experienced Rails >>>>> developer and I tried different things like: >> >>>>> 13 before :each do >>>>> 14 # @member = Factory.create(:member) >>>>> 15 request.env['warden'].stub(:authenticate!) { double(Member) } >>>>> 16 sign_in @member >>>>> 17 @person = Person.new >>>>> 18 end >> >>>>> which throws this error: >> >>>>> RuntimeError in 'PeopleController Methods should render form for a new >>>>> person on GET people#new' >>>>> Could not find a valid mapping for >>>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/mapping.rb:49:in >>>>> `find_scope!' >>>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: >>>>> 71:in `sign_in' >>>>> /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ >>>>> people_controller_spec.rb:16: >> >>>>> Finished in 0.437813 seconds >> >>>>> 23 examples, 1 failure >> >>>>> Thanks David, and sorry for asking too much about this issue. >> >>>> _______________________________________________ >>>> rspec-users mailing list >>>> rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users >>> _______________________________________________ >>> rspec-users mailing list >>> rspec-us... at rubyforge.org >>> http://rubyforge.org/mailman/listinfo/rspec-users >> >> _______________________________________________ >> rspec-users mailing list >> rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From daniel.amselem at gmail.com Sat Jul 10 16:53:52 2010 From: daniel.amselem at gmail.com (Daniel Salmeron Amselem) Date: Sat, 10 Jul 2010 13:53:52 -0700 (PDT) Subject: [rspec-users] Devise: session variable is empty on session_serializer.rb#store In-Reply-To: <889ACF8E-998F-4EFD-9A40-9653F45B7639@gmail.com> References: <68259a8d-e9a4-4a68-bd8f-6bfc26704826@k39g2000yqb.googlegroups.com> <557b1e51-1d5e-47c3-a553-b12ba40b9c68@k39g2000yqd.googlegroups.com> <64ef3984-22b5-4af6-b73c-a022ad698df5@a30g2000yqn.googlegroups.com> <51328b4b-26db-410a-92e1-2318446251aa@j4g2000yqh.googlegroups.com> <889ACF8E-998F-4EFD-9A40-9653F45B7639@gmail.com> Message-ID: <85e6b50c-fbf5-4a92-829f-7d82a291d59f@q12g2000yqj.googlegroups.com> Yep. I just changed current_member by @member, and it works now. Well, it's now asking me to create the "new" method which is what I expected to receive. Thanks, On Jul 10, 4:47?pm, David Chelimsky wrote: > On Jul 10, 2010, at 3:38 PM, Daniel Salmeron Amselem wrote: > > > You're right David, my fault. Than you very much for all your help. > > You got it working then? > > > > > > > On Jul 10, 4:32 pm, David Chelimsky wrote: > >> On Jul 10, 2010, at 3:21 PM, Daniel Salmeron Amselem wrote: > >>> On Jul 10, 3:53 pm, David Chelimsky wrote: > >>>> On Jul 10, 2010, at 2:45 PM, Daniel Salmeron Amselem wrote: > >>>>> On Jul 10, 2:31 pm, David Chelimsky wrote: > >>>>>> On Jul 10, 2010, at 1:26 PM, Daniel Salmeron Amselem wrote: > > >>>>>>> On Jul 9, 2:45 pm, Daniel Salmeron Amselem > >>>>>>> wrote: > >>>>>>>> I've been trying to test a very simple action on a controller with > >>>>>>>> this setup: > > >>>>>>>> rspec 1.3.0 > >>>>>>>> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] > >>>>>>>> Rails 2.3.8 > >>>>>>>> devise 1.0.8 > > >>>>>>>> And this is the test: > > >>>>>>>> ? ? before :each do > >>>>>>>> ? ? ? @member = Factory.create(:member) > >>>>>>>> ? ? ? sign_in @member > >>>>>>>> ? ? ? @person = Person.new > >>>>>>>> ? ? end > > >>>>>>>> ? ? it "should render form for a new person on GET people#new" do > >>>>>>>> ? ? ? current_member.should_receive(:build_person).and_return(@person) > > >>>>>>>> ? ? ? get :new > > >>>>>>>> ? ? ? assigns[:person].should == @person > >>>>>>>> ? ? ? response.should be_success > >>>>>>>> ? ? ? response.should render_template("new") > >>>>>>>> ? ? end > > >>>>>>>> This test creates a user, which is stored in the database with a > >>>>>>>> correct password. Running this test results in this error: > > >>>>>>>> 1) > >>>>>>>> NoMethodError in 'PeopleController Methods should render form for a > >>>>>>>> new person on GET people#new' > >>>>>>>> You have a nil object when you didn't expect it! > >>>>>>>> You might have expected an instance of ActiveRecord::Base. > >>>>>>>> The error occurred while evaluating nil.[]= > >>>>>>>> /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > >>>>>>>> session_serializer.rb:25:in `store' > >>>>>>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > >>>>>>>> 73:in `sign_in' > >>>>>>>> /Users/damselem/Documents/project/spec/controllers/ > >>>>>>>> people_controller_spec.rb:15: > > >>>>>>>> Finished in 0.625754 seconds > > >>>>>>>> 23 examples, 1 failure > > >>>>>>>> I wen to /Library/Ruby/Gems/1.8/gems/warden-0.10.4/lib/warden/ > >>>>>>>> session_serializer.rb and I changed the file in order to print out > >>>>>>>> some values: > > >>>>>>>> ? ?def store(user, scope) > >>>>>>>> ? ? ? return unless user > >>>>>>>> ? ? ? p scope > >>>>>>>> ? ? ? p key_for(scope) > >>>>>>>> ? ? ? p user > >>>>>>>> ? ? ? p serialize(user) > >>>>>>>> ? ? ? p session > >>>>>>>> ? ? ? session[key_for(scope)] = serialize(user) > >>>>>>>> ? ? end > > >>>>>>>> When running the test again I get: > > >>>>>>>> :member > > >>>>>>>> "warden.user.member.key" > > >>>>>>>> Member id: 1, email: "member2 at hv_club.com", encrypted_password: > >>>>>>>> "c79e5e4790643b284002bf6ad8045f53ff900afc", password_salt: > >>>>>>>> "Rim9LiyKARU1SHQCWIb0", confirmation_token: nil, confirmed_at: nil, > >>>>>>>> confirmation_sent_at: nil, reset_password_token: nil, remember_token: > >>>>>>>> nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: > >>>>>>>> nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: > >>>>>>>> nil, created_at: "2010-07-09 16:45:44", updated_at: "2010-07-09 > >>>>>>>> 16:45:44" > > >>>>>>>> [Member(id: integer, email: string, encrypted_password: string, > >>>>>>>> password_salt: string, confirmation_token: string, confirmed_at: > >>>>>>>> datetime, confirmation_sent_at: datetime, reset_password_token: > >>>>>>>> string, remember_token: string, remember_created_at: datetime, > >>>>>>>> sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: > >>>>>>>> datetime, current_sign_in_ip: string, last_sign_in_ip: string, > >>>>>>>> created_at: datetime, updated_at: datetime), 1] > > >>>>>>>> nil > > >>>>>>>> So it seems session is not initialized. Any ideas on how to fix this? > >>>>>>>> BTW, I already contacted Jose Valim through GitHub and he recommended > >>>>>>>> me to post my question in this group.http://github.com/plataformatec/devise/issues/issue/374 > > >>>>>>>> Thanks. > >>>>>>> I've been doing some research on this problem, and I found this > >>>>>>> discussion on Lighthouse:https://rspec.lighthouseapp.com/projects/5645/tickets/963-request-is-nil > > >>>>>>> As it seems, this is not a problem with Rails 3 anymore, but how can I > >>>>>>> make it work for rails 2.3.8? > > >>>>>> We've got this in an app using devise with rails 2.3.5 - should work with 2.3.8. > > >>>>>> ? ? before do > >>>>>> ? ? ? request.env['warden'].stub(:authenticate!) { double(User) } > >>>>>> ? ? end > > >>>>>> HTH, > >>>>>> David > >>>>> Thanks David, but could you explain me how should I use this before do > >>>>> block in order to sign in an user? > > >>>> That's all that's in the before. It effectively signs in the user. If you have a specific user you want to use, you can do > > >>>> user = Factory(:user) > >>>> ? request.env['warden'].stub(:authenticate!) { user } > >>> Oh, I tried that too, but then current_member doesn't work.... > > >>> 1) > >>> NameError in 'PeopleController Methods should render form for a new > >>> person on GET people#new' > >>> undefined local variable or method `current_member' for > >>> # > > >> This error is on the example itself, not the application code. Is there a reference to current_member in the spec itself? > > >>> /Library/Ruby/Gems/1.8/gems/actionpack-2.3.8/lib/action_controller/ > >>> test_process.rb:511:in `method_missing' > >>> /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ > >>> people_controller_spec.rb:21: > > >>> Finished in 0.543299 seconds > > >>> 23 examples, 1 failure > > >>> which it seems to be available when using devise: > >>>http://github.com/plataformatec/devise/tree/v1.0.8. Any idea? > >>>>> I am not a very experienced Rails > >>>>> developer and I tried different things like: > > >>>>> 13 ? ?before :each do > >>>>> 14 ? ? ?# @member = Factory.create(:member) > >>>>> 15 ? ? ?request.env['warden'].stub(:authenticate!) { double(Member) } > >>>>> 16 ? ? ?sign_in @member > >>>>> 17 ? ? ?@person = Person.new > >>>>> 18 ? ?end > > >>>>> which throws this error: > > >>>>> RuntimeError in 'PeopleController Methods should render form for a new > >>>>> person on GET people#new' > >>>>> Could not find a valid mapping for > >>>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/mapping.rb:49:in > >>>>> `find_scope!' > >>>>> /Library/Ruby/Gems/1.8/gems/devise-1.0.8/lib/devise/test_helpers.rb: > >>>>> 71:in `sign_in' > >>>>> /Users/damselem/Documents/Harvard/WebDev/hv_club/spec/controllers/ > >>>>> people_controller_spec.rb:16: > > >>>>> Finished in 0.437813 seconds > > >>>>> 23 examples, 1 failure > > >>>>> Thanks David, and sorry for asking too much about this issue. > > >>>> _______________________________________________ > >>>> rspec-users mailing list > >>>> rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users > >>> _______________________________________________ > >>> rspec-users mailing list > >>> rspec-us... at rubyforge.org > >>>http://rubyforge.org/mailman/listinfo/rspec-users > > >> _______________________________________________ > >> rspec-users mailing list > >> rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > > rspec-users mailing list > > rspec-us... at rubyforge.org > >http://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From mgehard at pivotallabs.com Tue Jul 6 11:43:45 2010 From: mgehard at pivotallabs.com (Mike Gehard) Date: Tue, 6 Jul 2010 09:43:45 -0600 Subject: [rspec-users] Strange behavior with using webrat in requests tests Message-ID: Good morning, I am using Rails3 (beta4) and RSpec2 (beta 15) under RVM and am running into an interesting issue. My request tests using webrat seem to think that they are running in the development Rails environment (I know this because I get all kinds of entries in the development log) and that is messing with Factory Girl (the factory_girl_rails gem). If I run "env" from the OSX command line, I have an entry for RAILS_ENV = development. After some poking around, I found the line: ENV["RAILS_ENV"] ||= 'test' in the spec_helper.rb file. I figured that this might be why webrat runs in the development environment since the above line won't do anything if RAILS_ENV is already set (which it is). If I remove the "||" from the above line, everything seems to work fine and webrat now stops putting stuff into the development log and puts stuff into the test log and the strangeness with factory_girl_rails goes away. I would like to confirm that removing the "||" from the spec_helper.rb file isn't going to mess with anything later down the road ro get an explanation as to why one wouldn't want to always force RAILS_ENV to be equal to "test" when running specs. Thanks, Mike -- Mike Gehard -------------- next part -------------- An HTML attachment was scrubbed... URL: From javaplayer at gmail.com Tue Jul 6 14:35:14 2010 From: javaplayer at gmail.com (Guilherme) Date: Tue, 6 Jul 2010 11:35:14 -0700 (PDT) Subject: [rspec-users] How to test a method that return random values Message-ID: <23a5b446-5f23-4394-a598-dd5d6ad9d211@w31g2000yqb.googlegroups.com> Hi, How can I test this method using rspec ? def self.generate_calculation number1, number2, operation number1 = rand(number1) number2 = rand(number2) ... end This method return an operation with those random numbers. Any tip ? From kmandrup.github at gmail.com Thu Jul 8 15:44:06 2010 From: kmandrup.github at gmail.com (Kristian Mandrup) Date: Thu, 8 Jul 2010 12:44:06 -0700 (PDT) Subject: [rspec-users] RSpec 2 equivalent for Rails::Generators::TestCase ? Message-ID: <5174f699-9963-4b60-a097-6d10d4b5a841@y11g2000yqm.googlegroups.com> I have been creating a lot of Thor generators and Rails generators during the past 4 months, but only this week did I find some good examples of how to write tests for generators using Rails::Generators::TestCase - in the "rails3-generators" project. I prefer to write my tests in RSpec 2, so I was wondering if there is an RSpec 2 equivalent out there yet? If not, I will try writing my own RSpec 2 port... but I would be very happy if anyone could help me in this effort, with suggestions or anything. Thanks! Kristian Test::Unit example ------------------------- require 'generator_helper' class Canable::Generators::ModelGeneratorTest < Rails::Generators::TestCase destination File.join(Rails.root) tests Canable::Generators::ModelGenerator setup :prepare_destination setup :copy_routes def assert_model(name, options) assert_file "app/models/#{name}.rb" do |account| assert_class name.camelize, account do |klass| assert_match /include Canable::Ables/, klass assert_match(/userstamps!/, klass) if options[:userstamps] if method = options[:method] assert_match(/def #{method}_by?(user)/, klass) if method end end end end test "invoke with no arguments" do run_generator end # test include Canable:Ables statement is added test "invoke with model name" do name = 'house' run_generator(name) assert_model(name) end end From kmandrup.github at gmail.com Thu Jul 8 17:10:20 2010 From: kmandrup.github at gmail.com (Kristian Mandrup) Date: Thu, 8 Jul 2010 14:10:20 -0700 (PDT) Subject: [rspec-users] Experimenting with converting Rails::Generators::TestCase to RSpec 2 Message-ID: http://github.com/kristianmandrup/canable/tree/master/spec/ Example: require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'Generator' do let(:generator) { Rails::Generators::Testcase.new } with generator do destination File.join(Rails.root) tests Canable::Generators::ModelGenerator setup :prepare_destination setup :copy_routes end it "should work" generator.run_generator generator.should generate_file('app/models/hello.rb') end end What do you think? From subbu9848155615 at gmail.com Fri Jul 9 02:28:02 2010 From: subbu9848155615 at gmail.com (siva) Date: Thu, 8 Jul 2010 23:28:02 -0700 (PDT) Subject: [rspec-users] Rspec-method missing error Message-ID: Hi Thanks in advance for helping me. I got the following error: /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/whiny_nil.rb:52:in `method_missing': undefined method `strip' for nil:NilClass (NoMethodError) from /usr/local/lib/ruby/1.8/net/http.rb:1142:in `initialize_http_header' from /usr/local/lib/ruby/1.8/net/http.rb:1140:in `each' from /usr/local/lib/ruby/1.8/net/http.rb:1140:in `initialize_http_header' from /usr/local/lib/ruby/1.8/net/http.rb:1472:in `initialize' from /usr/local/lib/ruby/1.8/net/http.rb:1588:in `initialize' from /usr/local/lib/ruby/1.8/net/http.rb:772:in `new' from /usr/local/lib/ruby/1.8/net/http.rb:772:in `get' from /usr/local/lib/ruby/gems/1.8/gems/cloudfiles-1.4.7/lib/ cloudfiles/authentication.rb:23:in `initialize' from /usr/local/lib/ruby/gems/1.8/gems/cloudfiles-1.4.7/lib/ cloudfiles/connection.rb:70:in `new' from /usr/local/lib/ruby/gems/1.8/gems/cloudfiles-1.4.7/lib/ cloudfiles/connection.rb:70:in `initialize' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/storage.rb:306:in `new' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/storage.rb:306:in `cloudfiles' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/storage.rb:310:in `create_container' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/storage.rb:316:in `cloudfiles_container' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/storage.rb:295:in `extended' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/storage.rb:290:in `instance_eval' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/storage.rb:290:in `extended' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/attachment.rb:334:in `extend' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/attachment.rb:334:in `initialize_storage' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip/attachment.rb:54:in `initialize' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip.rb:359:in `new' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip.rb:359:in `attachment_for' from /usr/local/lib/ruby/gems/1.8/gems/paperclip- cloudfiles-2.3.2/lib/paperclip.rb:257:in `avatar' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/validations.rb:466:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/validations.rb:466:in `validates_each' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/validations.rb:465:in `each' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/validations.rb:465:in `validates_each' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/callbacks.rb:182:in `call' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/callbacks.rb:182:in `evaluate_method' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/callbacks.rb:166:in `call' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/callbacks.rb:90:in `run' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/callbacks.rb:90:in `each' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/callbacks.rb:90:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/callbacks.rb:90:in `run' from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ active_support/callbacks.rb:276:in `run_callbacks' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/validations.rb:1098:in `valid_without_callbacks?' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/callbacks.rb:315:in `valid?' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/validations.rb:1077:in `save_without_dirty' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/dirty.rb:79:in `save_without_transactions' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/transactions.rb:229:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/transactions.rb:229:in `with_transaction_returning_status' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/connection_adapters/abstract/database_statements.rb: 136:in `transaction' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/transactions.rb:182:in `transaction' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/transactions.rb:228:in `with_transaction_returning_status' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/transactions.rb:196:in `save' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/transactions.rb:208:in `rollback_active_record_state!' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/transactions.rb:196:in `save' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ active_record/base.rb:723:in `create' from ./spec/models/user_spec.rb:57 from ./spec/models/user_spec.rb:56:in `each' from ./spec/models/user_spec.rb:56 from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ example/example_group_methods.rb:183:in `module_eval' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ example/example_group_methods.rb:183:in `subclass' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ example/example_group_methods.rb:55:in `describe' from ./spec/models/user_spec.rb:49 from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ example/example_group_methods.rb:183:in `module_eval' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ example/example_group_methods.rb:183:in `subclass' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ example/example_group_methods.rb:55:in `describe' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ example/example_group_factory.rb:31:in `create_example_group' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ dsl/main.rb:28:in `describe' from ./spec/models/user_spec.rb:37 from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ runner/example_group_runner.rb:15:in `load' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ runner/example_group_runner.rb:15:in `load_files' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ runner/example_group_runner.rb:14:in `each' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ runner/example_group_runner.rb:14:in `load_files' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ runner/options.rb:133:in `run_examples' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ runner/command_line.rb:9:in `run' from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/bin/spec:5 from /usr/local/bin/spec:19:in `load' from /usr/local/bin/spec:19 I didn't understand what is the root cause for this? So could please help me to get rid out this problem. It's urgent. Once again thanks for all... With Regards Siva From inspire22 at gmail.com Sat Jul 10 15:08:40 2010 From: inspire22 at gmail.com (Kevin) Date: Sat, 10 Jul 2010 12:08:40 -0700 (PDT) Subject: [rspec-users] does rspec2 work with datamapper? Message-ID: <039428f7-577c-46d5-8aba-38c56d131ff1@z34g2000pro.googlegroups.com> I keep getting this error message: /Users/kevin/.bundle/ruby/1.8/gems/rspec-rails-2.0.0.beta.16/lib/ rspec/ rails/fixture_support.rb:12: uninitialized constant RSpec::Rails::FixtureSupport::ActiveRecord (NameError) from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0.beta4/ lib/ active_support/concern.rb:17:in `class_eval' from /Library/Ruby/Gems/1.8/gems/activesupport- I've tried including require 'rails' in my application.rb, so it would load AR even though I'm not using it, but this didn't help. Any tips? Thanks! -Kevin From kmandrup.github at gmail.com Sun Jul 11 09:54:54 2010 From: kmandrup.github at gmail.com (Kristian Mandrup) Date: Sun, 11 Jul 2010 06:54:54 -0700 (PDT) Subject: [rspec-users] RSpec 2 - specs for Rails generators :) Message-ID: <8f74df97-28de-4024-9912-e31cbbbc3785@w31g2000yqb.googlegroups.com> http://github.com/kristianmandrup/canable In my fork of jnunemaker's canable I show my port of the unit test way of testing generators for RSpec 2. It still needs some tidying up to make it even more elegant ;) Feel free to provide suggestions etc. Kristian RSpec 2 example --- describe 'Generator' do before :each do remove_model_file 'account' end GeneratorSpec.with_generator 'Generator' do |g, c, gc| gc.tests Canable::Generators::ModelGenerator end it "should not work without a User mode file" do GeneratorSpec.with_generator do |g| g.run_generator %w{account} g.should_not generate_file('app/models/account.rb') end end it "should not work without a User mode file" do GeneratorSpec.with_generator do |g| create_model_file 'account' g.run_generator %w{account} g.should generate_file('app/models/account.rb') end end end From dchelimsky at gmail.com Sun Jul 11 21:41:05 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 11 Jul 2010 20:41:05 -0500 Subject: [rspec-users] does rspec2 work with datamapper? In-Reply-To: <039428f7-577c-46d5-8aba-38c56d131ff1@z34g2000pro.googlegroups.com> References: <039428f7-577c-46d5-8aba-38c56d131ff1@z34g2000pro.googlegroups.com> Message-ID: On Jul 10, 2010, at 2:08 PM, Kevin wrote > I keep getting this error message: > /Users/kevin/.bundle/ruby/1.8/gems/rspec-rails-2.0.0.beta.16/lib/ > rspec/ > rails/fixture_support.rb:12: uninitialized constant > RSpec::Rails::FixtureSupport::ActiveRecord (NameError) > from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0.beta4/ > lib/ > active_support/concern.rb:17:in `class_eval' > from /Library/Ruby/Gems/1.8/gems/activesupport- > > I've tried including require 'rails' in my application.rb, so it > would load AR even though I'm not using it, but this didn't help. What does your Gemfile look like? > > Any tips? Thanks! > -Kevin From dchelimsky at gmail.com Sun Jul 11 21:52:23 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 11 Jul 2010 20:52:23 -0500 Subject: [rspec-users] Strange behavior with using webrat in requests tests In-Reply-To: References: Message-ID: <9D818158-1095-431D-ABB8-1BE008FF0E1B@gmail.com> On Jul 6, 2010, at 10:43 AM, Mike Gehard wrote: > Good morning, > > I am using Rails3 (beta4) and RSpec2 (beta 15) under RVM and am running into an interesting issue. > > My request tests using webrat seem to think that they are running in the development Rails environment (I know this because I get all kinds of entries in the development log) and that is messing with Factory Girl (the factory_girl_rails gem). > > If I run "env" from the OSX command line, I have an entry for RAILS_ENV = development. Why do you have that? I'd get rid of this if you don't need it for something explicit. > After some poking around, I found the line: > ENV["RAILS_ENV"] ||= 'test' > > in the spec_helper.rb file. I figured that this might be why webrat runs in the development environment since the above line won't do anything if RAILS_ENV is already set (which it is). > > If I remove the "||" from the above line, everything seems to work fine and webrat now stops putting stuff into the development log and puts stuff into the test log and the strangeness with factory_girl_rails goes away. > > I would like to confirm that removing the "||" from the spec_helper.rb file isn't going to mess with anything later down the road ro get an explanation as to why one wouldn't want to always force RAILS_ENV to be equal to "test" when running specs. This shouldn't mess with anything else downstream. The ||= is there so you can set the environment to other special-case testing environments like this: RAILS_ENV=ci rake spec HTH, David > Thanks, > Mike > > -- > Mike Gehard > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Sun Jul 11 21:59:49 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 11 Jul 2010 20:59:49 -0500 Subject: [rspec-users] How to test a method that return random values In-Reply-To: <23a5b446-5f23-4394-a598-dd5d6ad9d211@w31g2000yqb.googlegroups.com> References: <23a5b446-5f23-4394-a598-dd5d6ad9d211@w31g2000yqb.googlegroups.com> Message-ID: On Jul 6, 2010, at 1:35 PM, Guilherme wrote: > Hi, > > How can I test this method using rspec ? > > def self.generate_calculation number1, number2, operation > number1 = rand(number1) > number2 = rand(number2) > ... > end > > This method return an operation with those random numbers. > > Any tip ? Something like this: OperationGenerator.stub(:rand).with(1).and_return(1) OperationGenerator.stub(:rand).with(2).and_return(2) expected = Addition.new(1,2) actual = OperationGenerator.generate_calculation 1, 2, Addition actual.should eq(expected) HTH, David From dchelimsky at gmail.com Sun Jul 11 22:31:50 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 11 Jul 2010 21:31:50 -0500 Subject: [rspec-users] Rspec-method missing error In-Reply-To: References: Message-ID: <3CD852B2-ED32-4594-8ECD-E9FA178FA80B@gmail.com> On Jul 9, 2010, at 1:28 AM, siva wrote: > Hi > > Thanks in advance for helping me. I got the following error: > > /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/whiny_nil.rb:52:in `method_missing': undefined method > `strip' for nil:NilClass (NoMethodError) > from /usr/local/lib/ruby/1.8/net/http.rb:1142:in > `initialize_http_header' > from /usr/local/lib/ruby/1.8/net/http.rb:1140:in `each' > from /usr/local/lib/ruby/1.8/net/http.rb:1140:in > `initialize_http_header' > from /usr/local/lib/ruby/1.8/net/http.rb:1472:in `initialize' > from /usr/local/lib/ruby/1.8/net/http.rb:1588:in `initialize' > from /usr/local/lib/ruby/1.8/net/http.rb:772:in `new' > from /usr/local/lib/ruby/1.8/net/http.rb:772:in `get' > from /usr/local/lib/ruby/gems/1.8/gems/cloudfiles-1.4.7/lib/ > cloudfiles/authentication.rb:23:in `initialize' > from /usr/local/lib/ruby/gems/1.8/gems/cloudfiles-1.4.7/lib/ > cloudfiles/connection.rb:70:in `new' > from /usr/local/lib/ruby/gems/1.8/gems/cloudfiles-1.4.7/lib/ > cloudfiles/connection.rb:70:in `initialize' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/storage.rb:306:in `new' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/storage.rb:306:in `cloudfiles' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/storage.rb:310:in `create_container' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/storage.rb:316:in > `cloudfiles_container' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/storage.rb:295:in `extended' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/storage.rb:290:in `instance_eval' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/storage.rb:290:in `extended' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/attachment.rb:334:in `extend' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/attachment.rb:334:in > `initialize_storage' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip/attachment.rb:54:in `initialize' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip.rb:359:in `new' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip.rb:359:in `attachment_for' > from /usr/local/lib/ruby/gems/1.8/gems/paperclip- > cloudfiles-2.3.2/lib/paperclip.rb:257:in `avatar' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/validations.rb:466:in `send' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/validations.rb:466:in `validates_each' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/validations.rb:465:in `each' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/validations.rb:465:in `validates_each' > from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/callbacks.rb:182:in `call' > from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/callbacks.rb:182:in `evaluate_method' > from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/callbacks.rb:166:in `call' > from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/callbacks.rb:90:in `run' > from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/callbacks.rb:90:in `each' > from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/callbacks.rb:90:in `send' > from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/callbacks.rb:90:in `run' > from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/ > active_support/callbacks.rb:276:in `run_callbacks' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/validations.rb:1098:in `valid_without_callbacks?' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/callbacks.rb:315:in `valid?' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/validations.rb:1077:in `save_without_dirty' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/dirty.rb:79:in `save_without_transactions' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/transactions.rb:229:in `send' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/transactions.rb:229:in > `with_transaction_returning_status' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/connection_adapters/abstract/database_statements.rb: > 136:in `transaction' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/transactions.rb:182:in `transaction' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/transactions.rb:228:in > `with_transaction_returning_status' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/transactions.rb:196:in `save' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/transactions.rb:208:in `rollback_active_record_state!' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/transactions.rb:196:in `save' > from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/ > active_record/base.rb:723:in `create' > from ./spec/models/user_spec.rb:57 > from ./spec/models/user_spec.rb:56:in `each' > from ./spec/models/user_spec.rb:56 > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > example/example_group_methods.rb:183:in `module_eval' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > example/example_group_methods.rb:183:in `subclass' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > example/example_group_methods.rb:55:in `describe' > from ./spec/models/user_spec.rb:49 > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > example/example_group_methods.rb:183:in `module_eval' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > example/example_group_methods.rb:183:in `subclass' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > example/example_group_methods.rb:55:in `describe' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > example/example_group_factory.rb:31:in `create_example_group' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > dsl/main.rb:28:in `describe' > from ./spec/models/user_spec.rb:37 > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > runner/example_group_runner.rb:15:in `load' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > runner/example_group_runner.rb:15:in `load_files' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > runner/example_group_runner.rb:14:in `each' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > runner/example_group_runner.rb:14:in `load_files' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > runner/options.rb:133:in `run_examples' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/lib/spec/ > runner/command_line.rb:9:in `run' > from /usr/local/lib/ruby/gems/1.8/gems/rspec-1.3.0/bin/spec:5 > from /usr/local/bin/spec:19:in `load' > from /usr/local/bin/spec:19 > > I didn't understand what is the root cause for this? So could > please help me to get rid out this problem. It's urgent. Once again > thanks for all... Please post some code and specs - can't tell much from the backtrace. Also, I'd recommend using gist or pastie - very difficult to read that backtrace in an email given the formatting. > With Regards > Siva > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From inspire22 at gmail.com Mon Jul 12 01:43:21 2010 From: inspire22 at gmail.com (Kevin) Date: Sun, 11 Jul 2010 22:43:21 -0700 (PDT) Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> Message-ID: <619f0960-b36a-4271-9e21-809596ecc7c4@x20g2000pro.googlegroups.com> Awesome discussion you've started here, very fun read for a new rspec follower. Just wanted to throw in that I've found setting a "cattr_accessor :current_user" in the user model to hold the current user to be very handy in terms of simplifying controllers. -Kevin From kmandrup.github at gmail.com Mon Jul 12 05:54:47 2010 From: kmandrup.github at gmail.com (Kristian Mandrup) Date: Mon, 12 Jul 2010 02:54:47 -0700 (PDT) Subject: [rspec-users] New project: rspec_for_generators - toolbox for using RSpec 2 to test and spec Rails 3 generators Message-ID: <84ab2e91-95e3-43f7-8fb5-34554280a3f8@r27g2000yqb.googlegroups.com> I have created a complete project where I have extracted all my RSpec 2 utilities, configurations, special matchers etc. for creating nice Rails 3 Generator specs. http://github.com/kristianmandrup/rspec_for_generators An example of use where all specs pass: http://github.com/kristianmandrup/canable Note: This was before I extracted the project so all the files are contained within the spec folder Please provide feedback, suggestions and fixes. Enjoy! Kristian From matt at mattwynne.net Mon Jul 12 12:02:20 2010 From: matt at mattwynne.net (Matt Wynne) Date: Mon, 12 Jul 2010 17:02:20 +0100 Subject: [rspec-users] (rspec2/rails3) spec'ing the details of a controller that is not purely *skinny* by design. In-Reply-To: <619f0960-b36a-4271-9e21-809596ecc7c4@x20g2000pro.googlegroups.com> References: <72060181-f84c-405d-aa6c-cd8f961681f4@t10g2000yqg.googlegroups.com> <619f0960-b36a-4271-9e21-809596ecc7c4@x20g2000pro.googlegroups.com> Message-ID: On 12 Jul 2010, at 06:43, Kevin wrote: > Awesome discussion you've started here, very fun read for a new rspec > follower. > > Just wanted to throw in that I've found setting a > "cattr_accessor :current_user" in the user model to hold the current > user to be very handy in terms of simplifying controllers. > > -Kevin Probably not the best idea if you're planning on having the app run on more than one thread or process though :) cheers, Matt http://blog.mattwynne.net +44(0)7974 430184 From lists at ruby-forum.com Mon Jul 12 12:44:16 2010 From: lists at ruby-forum.com (Rails Learner) Date: Mon, 12 Jul 2010 18:44:16 +0200 Subject: [rspec-users] RSpec Controller Testing - render_templte Issue Message-ID: <337d2f100423723595b44e3b2e9de8e3@ruby-forum.com> Hi! I am writing controller specs and getting a weird expectation failure. Here is the example. Please read the comments for details: it 'renders children/_show partial' do post :create, :child => @child # The line "response.should render_template('children/_show')" gives # me error: # ChildrenController when the enrollment form data is valid renders # children/_show partial' FAILED # expected "children/_show", got "children/_show_print_layout.html.erb" response.should render_template('children/_show') # This is weird. _show partial contains a button 'Print Form' and next #assertion passes, but the one above fails. response.should have_selector( 'input', :type => 'submit', :value => 'Print Form' ) response.should be_success end Many Thanks! -- Posted via http://www.ruby-forum.com/. From curtis.schofield at gmail.com Mon Jul 12 13:02:56 2010 From: curtis.schofield at gmail.com (Curtis j Schofield) Date: Mon, 12 Jul 2010 10:02:56 -0700 Subject: [rspec-users] RSpec Controller Testing - render_templte Issue In-Reply-To: <337d2f100423723595b44e3b2e9de8e3@ruby-forum.com> References: <337d2f100423723595b44e3b2e9de8e3@ruby-forum.com> Message-ID: On Mon, Jul 12, 2010 at 9:44 AM, Rails Learner wrote: > Hi! > > I am writing controller specs and getting a weird expectation failure. > Here is the example. Please read the comments for details: > > ? it 'renders children/_show partial' do > ? ? ?post :create, :child => @child > > ? ? ?# The line "response.should render_template('children/_show')" > gives > ? ? ?# me error: > ? ? ?# ChildrenController when the enrollment form data is valid > renders > ? ? ?# children/_show partial' FAILED > ? ? ?# expected "children/_show", got > "children/_show_print_layout.html.erb" > ? ? ?response.should render_template('children/_show') > > > ? ? ?# This is weird. _show partial contains a button 'Print Form' and > next #assertion passes, but the one above fails. > ? ? ?response.should have_selector( 'input', > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? :type => 'submit', > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? :value => 'Print Form' ) > ? ? ?response.should be_success > ? ?end > > Many Thanks! Please include your controller code for create! :d -- Make Haste Slowly From lists at ruby-forum.com Mon Jul 12 14:11:25 2010 From: lists at ruby-forum.com (Rails Learner) Date: Mon, 12 Jul 2010 20:11:25 +0200 Subject: [rspec-users] RSpec Controller Testing - render_templte Issue In-Reply-To: References: <337d2f100423723595b44e3b2e9de8e3@ruby-forum.com> Message-ID: <9d697bd89724f89a4bf4f05386469166@ruby-forum.com> Curtis j Schofield wrote: > On Mon, Jul 12, 2010 at 9:44 AM, Rails Learner > wrote: >> ? ? ?# me error: >> ? ? ?response.should have_selector( 'input', >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? :type => 'submit', >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? :value => 'Print Form' ) >> ? ? ?response.should be_success >> ? ?end >> >> Many Thanks! > > > Please include your controller code for create! :d > > > -- > Make Haste Slowly Hi Curtis, I figure out the issue. My controller has render_to_string that renders a pdf and then it renders the "_show" partial. Now there is another problem. How I can test both renders? Here is the controller code: def create @page_title = 'ASQ Enrollment Form' @child = Child.new(params[:child]) #Convert string to date. @child.EnrollmentDate = Date.strptime(@child.EnrollmentDate, '%Y-%m-%d') #Concatenate the date components and assign the complete date to ChildDob field @child.ChildDob = Date.strptime((params[:child]['ChildDob(2i)'] + '-' + params[:child]['ChildDob(3i)'] + '-' + params[:child]['ChildDob(1i)']), '%m-%d-%Y') unless ((params[:child]['ChildDob(1i)']).blank? || (params[:child]['ChildDob(2i)']).blank? || (params[:child]['ChildDob(3i)']).blank?) respond_to do |format| if @child.valid? FormMailer.deliver_enrollment_form(Date.today.strftime("%m-%d-%Y").to_s + ' - ASQ Enrollment Form - ' + @child.ChildFirstName + ' ' + @child.ChildLastName, @child, generate_pdf(@child, false)) flash.now[:notice] = 'ASQ Enrollment form was successfully submitted' #format.html { redirect_to(@child, :notice => 'Child was successfully created.') } format.html { render :partial => 'show', :locals => { :child => @child }, :layout => 'children' } format.xml { render :xml => @child, :status => :created, :location => @child } else format.html { render :action => 'new' } format.xml { render :xml => @child.errors, :status => :unprocessable_entity } end end end -- Posted via http://www.ruby-forum.com/. From curtis.schofield at gmail.com Mon Jul 12 15:11:14 2010 From: curtis.schofield at gmail.com (Curtis) Date: Mon, 12 Jul 2010 12:11:14 -0700 Subject: [rspec-users] RSpec Controller Testing - render_templte Issue In-Reply-To: <9d697bd89724f89a4bf4f05386469166@ruby-forum.com> References: <337d2f100423723595b44e3b2e9de8e3@ruby-forum.com> <9d697bd89724f89a4bf4f05386469166@ruby-forum.com> Message-ID: <28201AC4-E90D-4D19-B3A2-8101A3AED192@gmail.com> On Jul 12, 2010, at 11:11 AM, Rails Learner wrote: > Curtis j Schofield wrote: >> On Mon, Jul 12, 2010 at 9:44 AM, Rails Learner >> wrote: >>> # me error: >>> response.should have_selector( 'input', >>> :type => 'submit', >>> :value => 'Print Form' ) >>> response.should be_success >>> end >>> >>> Many Thanks! >> >> >> Please include your controller code for create! :d >> >> >> -- >> Make Haste Slowly > > Hi Curtis, > > I figure out the issue. > My controller has render_to_string that renders a pdf and then it > renders the "_show" partial. Now there is another problem. How I can > test both renders? > The format param is used for this case - it is used to set content- type properly - it is getting set by a route into a param var. Iirc format.pdf is possible aswell - I suspect that the mime type I'd already registered - it may not be. > Here is the controller code: > def create > @page_title = 'ASQ Enrollment Form' > @child = Child.new(params[:child]) > > #Convert string to date. > @child.EnrollmentDate = Date.strptime(@child.EnrollmentDate, > '%Y-%m-%d') > > #Concatenate the date components and assign the complete date to > ChildDob field > @child.ChildDob = Date.strptime((params[:child]['ChildDob(2i)'] + > '-' + params[:child]['ChildDob(3i)'] + '-' + > params[:child]['ChildDob(1i)']), '%m-%d-%Y') unless > ((params[:child]['ChildDob(1i)']).blank? || > (params[:child]['ChildDob(2i)']).blank? || > (params[:child]['ChildDob(3i)']).blank?) > > respond_to do |format| > if @child.valid? > FormMailer.deliver_enrollment_form(Date.today.strftime("%m-%d- > %Y").to_s > + ' - ASQ Enrollment Form - ' + @child.ChildFirstName + ' ' + > @child.ChildLastName, @child, generate_pdf(@child, false)) > flash.now[:notice] = 'ASQ Enrollment form was successfully > submitted' > #format.html { redirect_to(@child, :notice => 'Child was > successfully created.') } > format.html { render :partial => 'show', :locals => { :child => > @child }, :layout => 'children' } > format.xml { render :xml => @child, :status => :created, > :location => @child } > else > format.html { render :action => 'new' } > format.xml { render :xml => @child.errors, :status => > :unprocessable_entity } > end > end > 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 caifara.subscribe at gmail.com Tue Jul 13 08:25:03 2010 From: caifara.subscribe at gmail.com (Ivo Dancet) Date: Tue, 13 Jul 2010 14:25:03 +0200 Subject: [rspec-users] before(:all) to set up mocks and stubs Message-ID: <705E1D72-28EF-4CA3-B574-D4FC2E7A3876@gmail.com> Hi I'm upgrading an application to rspec2/rails3. A certain suite of tests, that generates a pdf document, uses a before(:all) filter to set the environment using mocks and stubs. Then the pdf gets generated and after that all the tests run on that same pdf document. In rspec2 it seems like I can only use mocks and stubs in in before(:each) filters (thus not in before(:all) filters). Has this been changed, or is this supposed to work (I may be doing something wrong)? Thanks From bewang.tech at gmail.com Tue Jul 13 12:29:53 2010 From: bewang.tech at gmail.com (Benyi Wang) Date: Tue, 13 Jul 2010 09:29:53 -0700 Subject: [rspec-users] [Rspec] Difference between stub and message expectation with any_number_of_times Message-ID: I'm wondering what's the difference between stub and message expectation with any_number_of_times, for example: myMock = mock("mymock") myMock.stub!(:is_a?).with(MyClass).and_return(false) and myMock = mock("mymock") myMock.should_receive(:is_a?).with(MyClass).any_number_of_times.and_return(false) because is_a? may not be called at all, it just like a stub. Is my understanding correct? Is there any guide how to use stub and message expectation? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at ruby-forum.com Tue Jul 13 13:50:10 2010 From: lists at ruby-forum.com (Rails Learner) Date: Tue, 13 Jul 2010 19:50:10 +0200 Subject: [rspec-users] RSpec Email-Spec Problem Message-ID: <98dabdabb0b3e4f399880db3f70535a6@ruby-forum.com> Hi! I am using email-spec gem with rspec to test email. If the email is multipart email then the example fails. The example passes if it's not multipart email. Any advise on how to get it to pass. Here is the error: 'Form Mailer should contain completed enrollment form in email body' FAILED expected /Enrollment Date:/, got "" Here is the example: it 'should contain completed enrollment form in email body' do @email.should have_text(/Enrollment Date:/) end Many thanks! -- Posted via http://www.ruby-forum.com/. From kit at nocturne.net.nz Tue Jul 13 18:05:55 2010 From: kit at nocturne.net.nz (Bayard Randel) Date: Wed, 14 Jul 2010 10:05:55 +1200 Subject: [rspec-users] before(:all) to set up mocks and stubs In-Reply-To: <705E1D72-28EF-4CA3-B574-D4FC2E7A3876@gmail.com> References: <705E1D72-28EF-4CA3-B574-D4FC2E7A3876@gmail.com> Message-ID: I know that generally it is not considered best practice to user before(:all) and after(:all) as state is shared between all examples, which is a unit-testing anti-pattern. The rspec book recommends setting up fixtures and environment for each example. Perhaps to drive this point home, support for this method has been dropped in rspec2? (just a guess) Bayard Randel nocturne.net.nz On 14 July 2010 00:25, Ivo Dancet wrote: > Hi > > I'm upgrading an application to rspec2/rails3. A certain suite of tests, > that generates a pdf document, uses a before(:all) filter to set the > environment using mocks and stubs. Then the pdf gets generated and after > that all the tests run on that same pdf document. In rspec2 it seems like I > can only use mocks and stubs in in before(:each) filters (thus not in > before(:all) filters). Has this been changed, or is this supposed to work (I > may be doing something wrong)? > > Thanks > _______________________________________________ > 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 inspire22 at gmail.com Tue Jul 13 18:12:41 2010 From: inspire22 at gmail.com (Kevin) Date: Tue, 13 Jul 2010 15:12:41 -0700 (PDT) Subject: [rspec-users] does rspec2 work with datamapper? In-Reply-To: References: <039428f7-577c-46d5-8aba-38c56d131ff1@z34g2000pro.googlegroups.com> Message-ID: <003faa85-acb1-4c57-88fb-266cd6baaf65@s24g2000pri.googlegroups.com> Thanks - I didn't have activerecord in the gemfile, thought I was loading it later. I still haven't quite wrapped my head around what uses the gemfile vs. other things, but it's working now! -Kevin On Jul 11, 6:41?pm, David Chelimsky wrote: > On Jul 10, 2010, at 2:08 PM, Kevin wrote > > > I keep getting this error message: > > /Users/kevin/.bundle/ruby/1.8/gems/rspec-rails-2.0.0.beta.16/lib/ > > rspec/ > > rails/fixture_support.rb:12: uninitialized constant > > RSpec::Rails::FixtureSupport::ActiveRecord (NameError) > > ? ? ? ?from /Library/Ruby/Gems/1.8/gems/activesupport-3.0.0.beta4/ > > lib/ > > active_support/concern.rb:17:in `class_eval' > > ? ? ? ?from /Library/Ruby/Gems/1.8/gems/activesupport- > > > I've tried including ? require 'rails' in my application.rb, so it > > would load AR even though I'm not using it, but this didn't help. > > What does your Gemfile look like? > > > > > Any tips? ?Thanks! > > -Kevin > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From ed.howland at gmail.com Tue Jul 13 18:14:54 2010 From: ed.howland at gmail.com (Ed Howland) Date: Tue, 13 Jul 2010 18:14:54 -0400 Subject: [rspec-users] [Rspec] Difference between stub and message expectation with any_number_of_times In-Reply-To: References: Message-ID: Ok, here is my stab at this: Since be seem to be only setting and testing bare mocks, I'd assume this is just useful to pass the mock as a stand in for some other object. So running a test: [See the code at pastie: http://pastie.org/1043160 ] I get subtly different messages: ) Spec::Mocks::MockExpectationError in 'mocking stub should not be ok if it gets a at least one good argument and an unexpected argument' Mock "mymock" received unexpected message :is_a? with (NoMock) ./mock_spec.rb:61: for stubs vs. ) Spec::Mocks::MockExpectationError in 'mocking mock should see the incorrect one and report an error' Mock "mymock" received :is_a? with unexpected arguments expected: (MyClass) got: (NoMock) ./mock_spec.rb:28: for mocks. The web page says: "Explicitly Imprecise Counts my_mock.should_receive(:msg).any_number_of_times The message can be received 0 or more times. " I can't envision a use case where this is needed, or can't be emulated via a stub. I'd be interested in David C's take or someone else's. Cheers, Ed Ed Howland http://greenprogrammer.wordpress.com http://twitter.com/ed_howland On Tue, Jul 13, 2010 at 12:29 PM, Benyi Wang wrote: > I'm wondering what's the difference between stub and message expectation > with any_number_of_times, for example: > myMock = mock("mymock") > myMock.stub!(:is_a?).with(MyClass).and_return(false) > and > myMock = mock("mymock") > myMock.should_receive(:is_a?).with(MyClass).any_number_of_times.and_return(false) > because is_a? may not be called at all, it just like a stub. Is my > understanding correct? > Is there any guide how to use stub and message expectation? > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From dchelimsky at gmail.com Tue Jul 13 18:19:14 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 13 Jul 2010 17:19:14 -0500 Subject: [rspec-users] before(:all) to set up mocks and stubs In-Reply-To: <705E1D72-28EF-4CA3-B574-D4FC2E7A3876@gmail.com> References: <705E1D72-28EF-4CA3-B574-D4FC2E7A3876@gmail.com> Message-ID: <8D74FAFB-29A6-4A2B-8236-CD25D85D31CE@gmail.com> On Jul 13, 2010, at 7:25 AM, Ivo Dancet wrote: > Hi > > I'm upgrading an application to rspec2/rails3. A certain suite of tests, that generates a pdf document, uses a before(:all) filter to set the environment using mocks and stubs. Then the pdf gets generated and after that all the tests run on that same pdf document. In rspec2 it seems like I can only use mocks and stubs in in before(:each) filters (thus not in before(:all) filters). Has this been changed, or is this supposed to work (I may be doing something wrong)? This should never have worked. Mocks and stubs are cleared out after each example, which means that even if you set them up before(:all), they'll only be set for the first example that runs, after which they go away. It sounds like you were unknowingly exploiting an unintentional feature. HTH, David From lists at ruby-forum.com Tue Jul 13 18:43:59 2010 From: lists at ruby-forum.com (Jonathan Rochkind) Date: Wed, 14 Jul 2010 00:43:59 +0200 Subject: [rspec-users] spec for a rails helper that renders a partial template Message-ID: So the stock answer to this is "don't do it". But I'm in a situation where it's really what I want to do to test what I want to test. a helper method: def some_helper render(:partial => "some/partial", :locals => {:some => some} end or even: def some_helper content = "" some_loop.each do |something| content << render(:partial => "some/partial", :locals => {:something => something} end end Is there any way to write a spec where I can test this kind of helper, and it really will render it's partial(s), and I can really write specs against the return strings? Any way at all? I've been trying for a while with no success. Thanks for any advice. Jonathan -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Tue Jul 13 19:02:01 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 13 Jul 2010 18:02:01 -0500 Subject: [rspec-users] spec for a rails helper that renders a partial template In-Reply-To: References: Message-ID: On Jul 13, 2010, at 5:43 PM, Jonathan Rochkind wrote: > So the stock answer to this is "don't do it". But I'm in a situation > where it's really what I want to do to test what I want to test. > > a helper method: > > def some_helper > render(:partial => "some/partial", :locals => {:some => some} > end > > or even: > > def some_helper > content = "" > some_loop.each do |something| > content << render(:partial => "some/partial", :locals => > {:something => something} > end > end > > Is there any way to write a spec where I can test this kind of helper, > and it really will render it's partial(s), and I can really write specs > against the return strings? > > Any way at all? I've been trying for a while with no success. Thanks for > any advice. RSpec version? From dchelimsky at gmail.com Tue Jul 13 19:04:12 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 13 Jul 2010 18:04:12 -0500 Subject: [rspec-users] [Rspec] Difference between stub and message expectation with any_number_of_times In-Reply-To: References: Message-ID: <44B9C616-54AB-4D92-97A5-2524FC85EB19@gmail.com> On Jul 13, 2010, at 11:29 AM, Benyi Wang wrote: > I'm wondering what's the difference between stub and message expectation with any_number_of_times, for example: > > myMock = mock("mymock") > myMock.stub!(:is_a?).with(MyClass).and_return(false) > > and > > myMock = mock("mymock") > myMock.should_receive(:is_a?).with(MyClass).any_number_of_times.and_return(false) > > because is_a? may not be called at all, it just like a stub. Is my understanding correct? Yes. > Is there any guide how to use stub and message expectation? any_number_of_times was introduced before we introduced stubs, way back, way back. I use stub() rather than should_receive + any_number_of_times. HTH, David From lists at ruby-forum.com Tue Jul 13 19:05:35 2010 From: lists at ruby-forum.com (Jonathan Rochkind) Date: Wed, 14 Jul 2010 01:05:35 +0200 Subject: [rspec-users] spec for a rails helper that renders a partial template In-Reply-To: References: Message-ID: <088f0b5aacb85d306fcca56ccfbea1d6@ruby-forum.com> David Chelimsky wrote: > On Jul 13, 2010, at 5:43 PM, Jonathan Rochkind wrote: > >> >> against the return strings? >> >> Any way at all? I've been trying for a while with no success. Thanks for >> any advice. > > RSpec version? Good point. Rails2, rspec 1.3.0. Thanks. -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Tue Jul 13 19:41:35 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 13 Jul 2010 18:41:35 -0500 Subject: [rspec-users] spec for a rails helper that renders a partial template In-Reply-To: <088f0b5aacb85d306fcca56ccfbea1d6@ruby-forum.com> References: <088f0b5aacb85d306fcca56ccfbea1d6@ruby-forum.com> Message-ID: <48BCD534-8DA9-4863-81B5-C2750308051E@gmail.com> On Jul 13, 2010, at 6:05 PM, Jonathan Rochkind wrote: > David Chelimsky wrote: >> On Jul 13, 2010, at 5:43 PM, Jonathan Rochkind wrote: >> >>> >>> against the return strings? >>> >>> Any way at all? I've been trying for a while with no success. Thanks for >>> any advice. >> >> RSpec version? > > Good point. Rails2, rspec 1.3.0. Thanks. Do you know about integrate_views? http://rspec.info/rails/writing/controllers.html From lists at ruby-forum.com Tue Jul 13 19:59:52 2010 From: lists at ruby-forum.com (Jonathan Rochkind) Date: Wed, 14 Jul 2010 01:59:52 +0200 Subject: [rspec-users] spec for a rails helper that renders a partial template In-Reply-To: <48BCD534-8DA9-4863-81B5-C2750308051E@gmail.com> References: <088f0b5aacb85d306fcca56ccfbea1d6@ruby-forum.com> <48BCD534-8DA9-4863-81B5-C2750308051E@gmail.com> Message-ID: David Chelimsky wrote: > On Jul 13, 2010, at 6:05 PM, Jonathan Rochkind wrote: > > Do you know about integrate_views? > > http://rspec.info/rails/writing/controllers.html I read about it in my quest through the documentation for a solution. This isn't actually a controller spec I'm trying to write, it's a helper spec. If I actually set it up as a helper spec... I don't seem to get "integrate_views", if I try to call it I get a method missing exception. Can I set it up as a controller spec, but then somehow still spec a helper method, rather than a controller? I thought of that, and tried to do it, but couldn't quite figure out how to do that. Any advice? Jonathan -- Posted via http://www.ruby-forum.com/. From akleak at gmail.com Tue Jul 13 21:49:02 2010 From: akleak at gmail.com (Arco) Date: Tue, 13 Jul 2010 18:49:02 -0700 (PDT) Subject: [rspec-users] Hiding test_unit Generators ? Message-ID: In a recent blog post, David wrote: Because RSpec is the test framework of record, Rails doesn?t know to hide the test_unit generators. If you want to hide them, just add this to one of your config files: Rails::Generators.hide_namespace("test_unit") Where exactly should this statement go?? I tried a number of alternatives and wasn't able to make it work. tx, Andy From lists at ruby-forum.com Wed Jul 14 08:22:26 2010 From: lists at ruby-forum.com (Rails Learner) Date: Wed, 14 Jul 2010 14:22:26 +0200 Subject: [rspec-users] RSpec Email-Spec Problem In-Reply-To: <98dabdabb0b3e4f399880db3f70535a6@ruby-forum.com> References: <98dabdabb0b3e4f399880db3f70535a6@ruby-forum.com> Message-ID: <708c08f499baded33bca9ac84a60620d@ruby-forum.com> Anyone, who can help? -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Wed Jul 14 08:45:02 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 14 Jul 2010 07:45:02 -0500 Subject: [rspec-users] Hiding test_unit Generators ? In-Reply-To: References: Message-ID: On Jul 13, 2010, at 8:49 PM, Arco wrote: > In a recent blog post, David wrote: > > Because RSpec is the test framework of record, Rails doesn?t know to > hide the test_unit generators. If you want to hide them, just add this > to one of your config files: > > Rails::Generators.hide_namespace("test_unit") > > Where exactly should this statement go?? I tried a number of > alternatives and wasn't able to make it work. Turns out this doesn't work as expected. I filed http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/5111 and am told it will be addressed in Rails proper. I'll update the blog post when I have more solid information. Sorry for the confusion. Cheers, David From cremes.devlist at mac.com Wed Jul 14 10:26:44 2010 From: cremes.devlist at mac.com (Chuck Remes) Date: Wed, 14 Jul 2010 09:26:44 -0500 Subject: [rspec-users] set expectation using self in constructor? Message-ID: I find myself using this pattern quite a bit. rspec 1.30 ruby 1.9.1, 1.9.2-rc2, jruby 1.51 all on osx 10.6.4 class Foo def initialize @bar = Bar.new end end context "init" do it "should allocate a helper class Bar" do Bar.should_receive(:new) Foo.new end end That all works well and as expected. Where I get stuck is when I change the signature for Bar to accept an argument from Foo like so: class Foo def initialize @bar = Bar.new self end end # try 1 context "init" do it "should allocate a helper class Bar" do Bar.should_receive(:new).with(self) # self refers to rspec here Foo.new end end # try 2 context "init" do let(:foo) { Foo.new } it "should allocate a helper class Bar" do Bar.should_receive(:new).with(foo) # foo is a different instance Foo.new end end # try 3 context "init" do it "should allocate a helper class Bar" do Bar.should_receive(:new).with(instance_of(Foo)) # works but seems wrong Foo.new end end I have tried lots of techniques for setting an argument expectation in my spec, but none of them work completely. How do others solve this? Or have I discovered a spec anti-pattern? If this is an anti-pattern, what is the suggested programming technique to avoid it? cr From lists at ruby-forum.com Wed Jul 14 10:40:20 2010 From: lists at ruby-forum.com (Rails Learner) Date: Wed, 14 Jul 2010 16:40:20 +0200 Subject: [rspec-users] RSpec Email-Spec Problem In-Reply-To: <708c08f499baded33bca9ac84a60620d@ruby-forum.com> References: <98dabdabb0b3e4f399880db3f70535a6@ruby-forum.com> <708c08f499baded33bca9ac84a60620d@ruby-forum.com> Message-ID: I have figure this out. I wanted to share this in case someone is having the same problem. I have taken a different route to test email body: Here is how my example looks now: it "should contain child's first name and last name in email body" do for part in @email.parts if part["Content-Type"].to_s =~ /^text\/html\W/ root = part.body assert_match '

New Enrollment Form for FakeFirstName FakeLastName

', root.to_s end end end Hope this will help someone. Thanks! -- Posted via http://www.ruby-forum.com/. From rick.denatale at gmail.com Wed Jul 14 11:18:44 2010 From: rick.denatale at gmail.com (Rick DeNatale) Date: Wed, 14 Jul 2010 11:18:44 -0400 Subject: [rspec-users] set expectation using self in constructor? In-Reply-To: References: Message-ID: On Wed, Jul 14, 2010 at 10:26 AM, Chuck Remes wrote: > I find myself using this pattern quite a bit. > > rspec 1.30 > ruby 1.9.1, 1.9.2-rc2, jruby 1.51 all on osx 10.6.4 > > class Foo > ?def initialize > ? ?@bar = Bar.new > ?end > end > > context "init" do > ?it "should allocate a helper class Bar" do > ? ?Bar.should_receive(:new) > ? ?Foo.new > ?end > end > > That all works well and as expected. Where I get stuck is when I change the signature for Bar to accept an argument from Foo like so: > > class Foo > ?def initialize > ? ?@bar = Bar.new self > ?end > end > > # try 1 > context "init" do > ?it "should allocate a helper class Bar" do > ? ?Bar.should_receive(:new).with(self) ?# self refers to rspec here > ? ?Foo.new > ?end > end > > # try 2 > context "init" do > ?let(:foo) { Foo.new } > > ?it "should allocate a helper class Bar" do > ? ?Bar.should_receive(:new).with(foo) ?# foo is a different instance > ? ?Foo.new > ?end > end > > # try 3 > context "init" do > ?it "should allocate a helper class Bar" do > ? ?Bar.should_receive(:new).with(instance_of(Foo)) # works but seems wrong > ? ?Foo.new > ?end > end > > I have tried lots of techniques for setting an argument expectation in my spec, but none of them work completely. How do others solve this? Or have I discovered a spec anti-pattern? > > If this is an anti-pattern, what is the suggested programming technique to avoid it? The problem is that the instance of Foo that you are testing for doesn't exist until you call Foo.new. I'd change this to spec the results rather than the implementation: e.g. foo = Foo.new foo.bar.should == foo Assuming that foo and bar have public accessors for bar and foo respectively. If not you can use instance_variable_get to 'get' around that. HTH -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Github: http://github.com/rubyredrick Twitter: @RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale From alexch at gmail.com Wed Jul 14 15:15:47 2010 From: alexch at gmail.com (Alex Chaffee) Date: Wed, 14 Jul 2010 12:15:47 -0700 (PDT) Subject: [rspec-users] Windowed comparison for differences in the middle of long strings Message-ID: When two strings fail to match, if the difference is somewhere in the middle of the strings, it can be annoying/impossible to track down the actual difference. I've written a little Comparison object that provides this kind of error message: Strings differ at position 12: expected: ..."efghijklmnopqrst"... actual: ..."efghijklXnopqrst"... It shows a "prelude" of a few characters, then the difference, on successive lines so they're easy to visually scan. It also does the right thing (or tries to) if the difference is near the beginning or end of the string (i.e. does or doesn't show ellipses). http://gist.github.com/474363 For people who can't wait for this to get incorporated into RSpec proper, you can require comparison.rb and it'll override the existing RSpec == matcher. Or wait for http://github.com/rspec/rspec-expectations/issues/issue/9 to be pulled into version 2.1 (maybe). One open question is whether the exception message should show the full actual string as well as the comparison... On one hand, it adds to screen clutter, but on the other hand, it can be important in tracking down the problem, especially if the prelude is ambiguous. From matt at mattwynne.net Wed Jul 14 17:20:49 2010 From: matt at mattwynne.net (Matt Wynne) Date: Wed, 14 Jul 2010 22:20:49 +0100 Subject: [rspec-users] set expectation using self in constructor? In-Reply-To: References: Message-ID: On 14 Jul 2010, at 15:26, Chuck Remes wrote: > I find myself using this pattern quite a bit. > > rspec 1.30 > ruby 1.9.1, 1.9.2-rc2, jruby 1.51 all on osx 10.6.4 > > class Foo > def initialize > @bar = Bar.new > end > end > > context "init" do > it "should allocate a helper class Bar" do > Bar.should_receive(:new) > Foo.new > end > end > > That all works well and as expected. Where I get stuck is when I change the signature for Bar to accept an argument from Foo like so: > > class Foo > def initialize > @bar = Bar.new self > end > end > > # try 1 > context "init" do > it "should allocate a helper class Bar" do > Bar.should_receive(:new).with(self) # self refers to rspec here > Foo.new > end > end > > # try 2 > context "init" do > let(:foo) { Foo.new } > > it "should allocate a helper class Bar" do > Bar.should_receive(:new).with(foo) # foo is a different instance > Foo.new > end > end > > # try 3 > context "init" do > it "should allocate a helper class Bar" do > Bar.should_receive(:new).with(instance_of(Foo)) # works but seems wrong > Foo.new > end > end > > I have tried lots of techniques for setting an argument expectation in my spec, but none of them work completely. How do others solve this? Or have I discovered a spec anti-pattern? > > If this is an anti-pattern, what is the suggested programming technique to avoid it? You can do this, by using a test spy to remember the value of foo passed into the stubbed constructor and then later comparing it: let(:foo) { Foo.new } it "should allocate a helper class Foo" do actual_foo = Bar.should_receive(:new) do |the_foo| the_foo end actual_foo.should == foo end Whether you want to do this though, is another question. I think it's a bit of an anti-pattern personally. I'd probably let acceptance tests catch mistakes in this kind of thing, and concentrate on speccing the interaction between Foo and Bar once you've got the instances spun up. > > cr > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users cheers, Matt http://blog.mattwynne.net +44(0)7974 430184 From rogerpack2005 at gmail.com Wed Jul 14 20:44:32 2010 From: rogerpack2005 at gmail.com (rogerdpack) Date: Wed, 14 Jul 2010 17:44:32 -0700 (PDT) Subject: [rspec-users] pending blocks Message-ID: Would it be possible to have pending be accessible everywhere? Curgem rently with describe '' do pending 'abc' do end end yields: C:\dev\ruby\universal-scene-skipper\spec>spec small.spec C:/dev/ruby/universal-scene-skipper/spec/small.spec:3: undefined method `pending' for Spec::Example::ExampleGroup::Subclass_1:Class (NoMethodError) from C:/installs/ruby-1.8.6-p388-i386-mingw32/lib/ruby/gems/ 1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:183:in `module_eval' I believe. Thanks! From dchelimsky at gmail.com Wed Jul 14 20:50:58 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 14 Jul 2010 19:50:58 -0500 Subject: [rspec-users] pending blocks In-Reply-To: References: Message-ID: On Jul 14, 2010, at 7:44 PM, rogerdpack wrote: > Would it be possible to have pending be accessible everywhere? > > Curgem rently with > > describe '' do > pending 'abc' do > end > end In rspec-2, you can do this: describe "something", :pending => true do ... end And all the examples in that group are pending. HTH, David > > yields: > > C:\dev\ruby\universal-scene-skipper\spec>spec small.spec > C:/dev/ruby/universal-scene-skipper/spec/small.spec:3: undefined > method `pending' for Spec::Example::ExampleGroup::Subclass_1:Class > (NoMethodError) > from C:/installs/ruby-1.8.6-p388-i386-mingw32/lib/ruby/gems/ > 1.8/gems/rspec-1.3.0/lib/spec/example/example_group_methods.rb:183:in > `module_eval' > > I believe. > Thanks! > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From caifara.subscribe at gmail.com Thu Jul 15 04:02:30 2010 From: caifara.subscribe at gmail.com (Ivo Dancet) Date: Thu, 15 Jul 2010 10:02:30 +0200 Subject: [rspec-users] before(:all) to set up mocks and stubs In-Reply-To: <8D74FAFB-29A6-4A2B-8236-CD25D85D31CE@gmail.com> References: <705E1D72-28EF-4CA3-B574-D4FC2E7A3876@gmail.com> <8D74FAFB-29A6-4A2B-8236-CD25D85D31CE@gmail.com> Message-ID: <02C3B57C-2B81-4528-A3B8-ADF7E5322E78@gmail.com> Thanks for your answers. I'll use a fixture replacement to set up the environment. I know that this (using before(:all) to setup a state) is not a best practice. In this case however, I would consider my approach to be acceptable as the pdf takes a long time to generate. All tests run on the same pdf so generating it 30 times would be a waste of time and effort. Using mocks and stubs made the generating part even more efficient. Making real objects will do the job just a tiny bit slower. I can live with that. Thanks again. Op 14-jul-2010, om 00:19 heeft David Chelimsky het volgende geschreven: > On Jul 13, 2010, at 7:25 AM, Ivo Dancet wrote: > >> Hi >> >> I'm upgrading an application to rspec2/rails3. A certain suite of tests, that generates a pdf document, uses a before(:all) filter to set the environment using mocks and stubs. Then the pdf gets generated and after that all the tests run on that same pdf document. In rspec2 it seems like I can only use mocks and stubs in in before(:each) filters (thus not in before(:all) filters). Has this been changed, or is this supposed to work (I may be doing something wrong)? > > This should never have worked. Mocks and stubs are cleared out after each example, which means that even if you set them up before(:all), they'll only be set for the first example that runs, after which they go away. > > It sounds like you were unknowingly exploiting an unintentional feature. > > HTH, > David > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Thu Jul 15 09:16:29 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 15 Jul 2010 08:16:29 -0500 Subject: [rspec-users] spec for a rails helper that renders a partial template In-Reply-To: References: <088f0b5aacb85d306fcca56ccfbea1d6@ruby-forum.com> <48BCD534-8DA9-4863-81B5-C2750308051E@gmail.com> Message-ID: <654FF708-6FB8-4124-8760-17CE88DFFB1A@gmail.com> On Jul 13, 2010, at 6:59 PM, Jonathan Rochkind wrote: > David Chelimsky wrote: >> On Jul 13, 2010, at 6:05 PM, Jonathan Rochkind wrote: >> >> Do you know about integrate_views? >> >> http://rspec.info/rails/writing/controllers.html > > I read about it in my quest through the documentation for a solution. > > This isn't actually a controller spec I'm trying to write, it's a helper > spec. If I actually set it up as a helper spec... I don't seem to get > "integrate_views", if I try to call it I get a method missing exception. > > Can I set it up as a controller spec, but then somehow still spec a > helper method, rather than a controller? I thought of that, and tried > to do it, but couldn't quite figure out how to do that. Any advice? I don't think there's a good way to do that in RSpec-1. In RSpec-2, however, you should be able to do this in a regular helper spec. HTH, David > Jonathan From cremes.devlist at mac.com Thu Jul 15 09:42:03 2010 From: cremes.devlist at mac.com (Chuck Remes) Date: Thu, 15 Jul 2010 08:42:03 -0500 Subject: [rspec-users] set expectation using self in constructor? In-Reply-To: References: Message-ID: <4AC65624-1CDF-4CDD-8B21-207B4EB122C7@mac.com> On Jul 14, 2010, at 4:20 PM, Matt Wynne wrote: > > You can do this, by using a test spy to remember the value of foo passed into the stubbed constructor and then later comparing it: > > let(:foo) { Foo.new } > > it "should allocate a helper class Foo" do > actual_foo = Bar.should_receive(:new) do |the_foo| > the_foo > end > actual_foo.should == foo > end > > Whether you want to do this though, is another question. I think it's a bit of an anti-pattern personally. I'd probably let acceptance tests catch mistakes in this kind of thing, and concentrate on speccing the interaction between Foo and Bar once you've got the instances spun up. This is an interesting technique. I didn't realize that using the block form of expectations/matchers returned a value. Thanks for the tip! cr From cremes.devlist at mac.com Thu Jul 15 09:55:27 2010 From: cremes.devlist at mac.com (Chuck Remes) Date: Thu, 15 Jul 2010 08:55:27 -0500 Subject: [rspec-users] set expectation using self in constructor? In-Reply-To: References: Message-ID: <9A96B91E-78AB-4D23-897C-D9DFCFF24E93@mac.com> On Jul 14, 2010, at 4:20 PM, Matt Wynne wrote: > > You can do this, by using a test spy to remember the value of foo passed into the stubbed constructor and then later comparing it: > > let(:foo) { Foo.new } > > it "should allocate a helper class Foo" do > actual_foo = Bar.should_receive(:new) do |the_foo| > the_foo > end > actual_foo.should == foo > end > > Whether you want to do this though, is another question. I think it's a bit of an anti-pattern personally. I'd probably let acceptance tests catch mistakes in this kind of thing, and concentrate on speccing the interaction between Foo and Bar once you've got the instances spun up. For those following along at home, this exact technique did not work. The +actual_foo+ variable was holding some mock value instead of the real self value. I fixed it by assigning to a variable inside the block that had been defined outside the block (avoiding block scope issues). let(:foo) { Foo.new } it "should allocate a helper class Foo" do actual_foo = nil Bar.should_receive(:new) do |the_foo| actual_foo = the_foo end actual_foo.should == foo end This succeeds. Thanks to all for your help. cr From lists at ruby-forum.com Thu Jul 15 10:57:39 2010 From: lists at ruby-forum.com (Jonathan Rochkind) Date: Thu, 15 Jul 2010 16:57:39 +0200 Subject: [rspec-users] spec for a rails helper that renders a partial template In-Reply-To: <654FF708-6FB8-4124-8760-17CE88DFFB1A@gmail.com> References: <088f0b5aacb85d306fcca56ccfbea1d6@ruby-forum.com> <48BCD534-8DA9-4863-81B5-C2750308051E@gmail.com> <654FF708-6FB8-4124-8760-17CE88DFFB1A@gmail.com> Message-ID: David Chelimsky wrote: > > I don't think there's a good way to do that in RSpec-1. In RSpec-2, > however, you should be able to do this in a regular helper spec. Okay, thanks. Can't wait until I get my app migrated to Rails3, glad that Rspec has improved in flexibility in a great many ways, it appears, in Rspec2/Rails3. -- Posted via http://www.ruby-forum.com/. From gditrick at fuse.net Thu Jul 15 13:18:44 2010 From: gditrick at fuse.net (Greg Ditrick) Date: Thu, 15 Jul 2010 13:18:44 -0400 Subject: [rspec-users] Questions about testing a module method that randomly creates stuff from list. Message-ID: <12292557.1279214324721.JavaMail.root@wmvirt66> All, I have a method in a shared Module that shuffles data and then output other data. The method is somewhat large (maybe 50 lines) and sometimes calls other sub methods to help to complete the output which must meet a specific criteria or it re-shuffles. My questions are: 1) How do I capture that a sub method is called? Module.should_recieve(:sub_method) ??? 2) How do I capture the rand number that caused a condition (like the :sub_method being called, an Error raised, etc.). I know srand will give me the seed that caused it. But, how do I capture it on the failure? For example: true.should_not be_true || File.open(?capture_rand.out?,?a?) { |f| f.puts ?#{srand}?} Can you do an || (or) statement like that and have it capture the seed and fail the example? Any ideas? Any other ways of capturing data like that? After I capture the seeds, I?m thinking I could than use those seeds to fine tune specific tests. Thanks, GregD From gditrick at fuse.net Thu Jul 15 13:26:52 2010 From: gditrick at fuse.net (GregD) Date: Thu, 15 Jul 2010 10:26:52 -0700 (PDT) Subject: [rspec-users] Questions about testing a module method that randomly creates stuff from list. Message-ID: <0e87480f-ebef-4e76-a7cb-06193931ae7b@e30g2000vbl.googlegroups.com> All, I have a method in a shared Module that shuffles data and then output other data. The method is somewhat large (maybe 50 lines) and sometimes calls other sub methods to help to complete the output which must meet a specific criteria or it re-shuffles. My questions are: 1) How do I capture that a sub method is called? Module.should_recieve(:sub_method) ??? 2) How do I capture the rand number that caused a condition (like the :sub_method being called, an Error raised, etc.). I know srand will give me the seed that caused it. But, how do I capture it on the failure? For example: true.should_not be_true || File.open(?capture_rand.out?,?a?) { |f| f.puts ?#{srand}?} Can you do an || (or) statement like that and have it capture the seed and fail the example? Any ideas? Any other ways of capturing data like that? After I capture the seeds, I?m thinking I could than use those seeds to fine tune specific tests. Thanks, GregD From mihirp at amazon.com Thu Jul 15 13:36:02 2010 From: mihirp at amazon.com (Patel, Mihir) Date: Thu, 15 Jul 2010 10:36:02 -0700 Subject: [rspec-users] Help needed for instslling rspec Message-ID: <164969DEADC6FB4E8F1494DA3D34E98B03DC1E2F@EX-SEA19-A.ant.amazon.com> Hi All, I am new to BDD. I have ruby 1.8.7 on my RHEL5 computer. I am trying to install RSpec by "gem install rspec" but I get an error saying : "could not find rspec locally or in a repository", Please help me out. Regards, [ Mihir Patel | SDE Intern | +919 889 9537 | mihirp at amazon.com ] -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Thu Jul 15 13:48:43 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 15 Jul 2010 12:48:43 -0500 Subject: [rspec-users] Help needed for instslling rspec In-Reply-To: <164969DEADC6FB4E8F1494DA3D34E98B03DC1E2F@EX-SEA19-A.ant.amazon.com> References: <164969DEADC6FB4E8F1494DA3D34E98B03DC1E2F@EX-SEA19-A.ant.amazon.com> Message-ID: <468611FE-587A-4768-92C9-D79A674C1668@gmail.com> On Jul 15, 2010, at 12:36 PM, Patel, Mihir wrote: > Hi All, > I am new to BDD. I have ruby 1.8.7 on my RHEL5 computer. I am trying to install RSpec by ?gem install rspec? but I get an error saying : ?could not find rspec locally or in a repository?, Please help me out. Please type "gem env" in a shell and post back the output. > > Regards, > [ Mihir Patel | SDE Intern | +919 889 9537 | mihirp at amazon.com ] -------------- next part -------------- An HTML attachment was scrubbed... URL: From ericmilford at gmail.com Thu Jul 15 18:53:22 2010 From: ericmilford at gmail.com (ericindc) Date: Thu, 15 Jul 2010 15:53:22 -0700 (PDT) Subject: [rspec-users] Heckle & RSpec 2 Message-ID: <3867e2fc-528e-44d3-87f4-3670b930b6ee@y4g2000yqy.googlegroups.com> How do I run Heckle with RSpec? I've tried rake spec --heckle but get no output. I've tried just -heckle too, as mentioned in the docs, but that isn't accepted as a valid option and the help out is displayed. I have both the heckle and rspec-rails gems in my Gemfile, and running Rails 3, and have the latest beta version (at the time 17) installed. Thanks. From mkolenda at gmail.com Thu Jul 15 19:24:28 2010 From: mkolenda at gmail.com (Matt Kolenda) Date: Thu, 15 Jul 2010 16:24:28 -0700 Subject: [rspec-users] rspec route question Message-ID: Hello I'm having some trouble getting rspec to recognize a route. # This works describe "routes" do it "should have a route" do { :get => "/accounts/3/jobs/3/ applications/1/edit" }.should route_to(:controller => 'applications', :action => 'edit', :id => "1", :account_id => "3", :job_id => "3" ) end end # This fails describe "#edit" do it "should respond to application/edit" do get "#{edit_account_job_application_path(@account.id, @job.id, @ application.id)}" response.should be_success end end Here is the stack trace 1) ActionController::RoutingError in 'ApplicationsController#edit should respond to application/edit' No route matches {:action=>"/accounts/23/jobs/ 99/applications/299/edit", :controller=>"applications"} /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:419:in `generate' /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:352:in `generate_extras' /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:348:in `extra_keys' /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/test_process.rb:96:in `assign_parameters' /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/test_process.rb:440:in `process' /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/test_process.rb:398:in `get' ./spec/controllers/applications_controller_spec.rb:26: Note that this route works fine at runtime in the browser. Also rails is able to resolve the route "edit_account_job_application_path". I'm running rspec 1.3.0 and rspec-rails 1.3.2 Thanks in advance! Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Thu Jul 15 20:16:02 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 15 Jul 2010 19:16:02 -0500 Subject: [rspec-users] Heckle & RSpec 2 In-Reply-To: <3867e2fc-528e-44d3-87f4-3670b930b6ee@y4g2000yqy.googlegroups.com> References: <3867e2fc-528e-44d3-87f4-3670b930b6ee@y4g2000yqy.googlegroups.com> Message-ID: <072EF423-9954-40DA-A3B0-B6ED74D16113@gmail.com> On Jul 15, 2010, at 5:53 PM, ericindc wrote: > How do I run Heckle with RSpec? I've tried rake spec --heckle but get > no output. I've tried just -heckle too, as mentioned in the docs, but > that isn't accepted as a valid option and the help out is displayed. > I have both the heckle and rspec-rails gems in my Gemfile, and running > Rails 3, and have the latest beta version (at the time 17) installed. RSpec-2 doesn't support Heckle yet. Not sure if it will, given no plans to support Heckle on Ruby 1.9. Cheers, David From matt at mattwynne.net Fri Jul 16 05:29:52 2010 From: matt at mattwynne.net (Matt Wynne) Date: Fri, 16 Jul 2010 10:29:52 +0100 Subject: [rspec-users] set expectation using self in constructor? In-Reply-To: <9A96B91E-78AB-4D23-897C-D9DFCFF24E93@mac.com> References: <9A96B91E-78AB-4D23-897C-D9DFCFF24E93@mac.com> Message-ID: <75A0B665-BBA5-4CBF-AC59-FD0BC54DDB64@mattwynne.net> On 15 Jul 2010, at 14:55, Chuck Remes wrote: > > On Jul 14, 2010, at 4:20 PM, Matt Wynne wrote: > >> >> You can do this, by using a test spy to remember the value of foo passed into the stubbed constructor and then later comparing it: >> >> let(:foo) { Foo.new } >> >> it "should allocate a helper class Foo" do >> actual_foo = Bar.should_receive(:new) do |the_foo| >> the_foo >> end >> actual_foo.should == foo >> end >> >> Whether you want to do this though, is another question. I think it's a bit of an anti-pattern personally. I'd probably let acceptance tests catch mistakes in this kind of thing, and concentrate on speccing the interaction between Foo and Bar once you've got the instances spun up. > > For those following along at home, this exact technique did not work. The +actual_foo+ variable was holding some mock value instead of the real self value. Sorry. Do we think this is a bug in rspec? I'd have expected the block to return the last evaluated value. But is that just me? > > I fixed it by assigning to a variable inside the block that had been defined outside the block (avoiding block scope issues). > > let(:foo) { Foo.new } > > it "should allocate a helper class Foo" do > actual_foo = nil > Bar.should_receive(:new) do |the_foo| > actual_foo = the_foo > end > > actual_foo.should == foo > end > > This succeeds. > > Thanks to all for your help. > > cr > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users cheers, Matt http://blog.mattwynne.net +44(0)7974 430184 From tom at experthuman.com Fri Jul 16 05:45:53 2010 From: tom at experthuman.com (Tom Stuart) Date: Fri, 16 Jul 2010 10:45:53 +0100 Subject: [rspec-users] set expectation using self in constructor? In-Reply-To: <75A0B665-BBA5-4CBF-AC59-FD0BC54DDB64@mattwynne.net> References: <9A96B91E-78AB-4D23-897C-D9DFCFF24E93@mac.com> <75A0B665-BBA5-4CBF-AC59-FD0BC54DDB64@mattwynne.net> Message-ID: On 16 Jul 2010, at 10:29, Matt Wynne wrote: >> For those following along at home, this exact technique did not work. The +actual_foo+ variable was holding some mock value instead of the real self value. > Sorry. Do we think this is a bug in rspec? I'd have expected the block to return the last evaluated value. But is that just me? It doesn't look like a bug to me -- I expect #should_receive to return a message expectation, e.g. so that I can call #with/#and_return on it, and it would seem weird for it to behave otherwise when a block is supplied. Cheers, -Tom From dchelimsky at gmail.com Fri Jul 16 07:09:17 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 16 Jul 2010 06:09:17 -0500 Subject: [rspec-users] set expectation using self in constructor? In-Reply-To: References: <9A96B91E-78AB-4D23-897C-D9DFCFF24E93@mac.com> <75A0B665-BBA5-4CBF-AC59-FD0BC54DDB64@mattwynne.net> Message-ID: On Jul 16, 2010, at 4:45 AM, Tom Stuart wrote: > On 16 Jul 2010, at 10:29, Matt Wynne wrote: >>> For those following along at home, this exact technique did not work. The +actual_foo+ variable was holding some mock value instead of the real self value. >> Sorry. Do we think this is a bug in rspec? I'd have expected the block to return the last evaluated value. But is that just me? > > It doesn't look like a bug to me -- I expect #should_receive to return a message expectation, e.g. so that I can call #with/#and_return on it, and it would seem weird for it to behave otherwise when a block is supplied. Correct. The block syntax is an alternative to and_returns, and_yields, and_raises, etc. The block is evaluated lazily, when the stubbed or mocked method is invoked. HTH, David > Cheers, > -Tom > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From matt at mattwynne.net Fri Jul 16 07:14:36 2010 From: matt at mattwynne.net (Matt Wynne) Date: Fri, 16 Jul 2010 12:14:36 +0100 Subject: [rspec-users] set expectation using self in constructor? In-Reply-To: References: <9A96B91E-78AB-4D23-897C-D9DFCFF24E93@mac.com> <75A0B665-BBA5-4CBF-AC59-FD0BC54DDB64@mattwynne.net> Message-ID: <3FD57F57-D5E9-4236-BD10-FAB4949E235A@mattwynne.net> On 16 Jul 2010, at 10:45, Tom Stuart wrote: > On 16 Jul 2010, at 10:29, Matt Wynne wrote: >>> For those following along at home, this exact technique did not work. The +actual_foo+ variable was holding some mock value instead of the real self value. >> Sorry. Do we think this is a bug in rspec? I'd have expected the block to return the last evaluated value. But is that just me? > > It doesn't look like a bug to me -- I expect #should_receive to return a message expectation, e.g. so that I can call #with/#and_return on it, and it would seem weird for it to behave otherwise when a block is supplied. > > Cheers, > -Tom Of course, silly me. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users cheers, Matt http://blog.mattwynne.net +44(0)7974 430184 From dchelimsky at gmail.com Fri Jul 16 07:19:53 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 16 Jul 2010 06:19:53 -0500 Subject: [rspec-users] rspec route question In-Reply-To: References: Message-ID: <8CD9A709-A529-4D29-8572-0865D9A2A885@gmail.com> On Jul 15, 2010, at 6:24 PM, Matt Kolenda wrote: > Hello > > I'm having some trouble getting rspec to recognize a route. > > # This works > describe "routes" do > it "should have a route" do > { :get => "/accounts/3/jobs/3/ > applications/1/edit" }.should route_to(:controller => 'applications', :action => 'edit', :id => "1", :account_id => "3", :job_id => "3" ) > end > end > > # This fails > describe "#edit" do > it "should respond to application/edit" do > get "#{edit_account_job_application_path(@account.id, @job.id, @application.id)}" > response.should be_success > end > end Controller specs include behavior from ActionController::TestCase, which is designed to handle requests using a hash representing the action and params rather than a URL (or route). The proper way to do this is: get :edit, :id => @application.id, :job_id => @job.id, :account_id => @account_id If you want to, you can use urls in request specs in rspec-rails-2 (integration specs in rspec-rails-1). But I wouldn't recommend that unless you feel you'll benefit from going through routing and rendering views. HTH, David > > Here is the stack trace > 1) > ActionController::RoutingError in 'ApplicationsController#edit should respond to application/edit' > No route matches {:action=>"/accounts/23/jobs/ > 99/applications/299/edit", :controller=>"applications"} > /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:419:in `generate' > /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:352:in `generate_extras' > /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:348:in `extra_keys' > /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/test_process.rb:96:in `assign_parameters' > /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/test_process.rb:440:in `process' > /Library/Ruby/Gems/1.8/gems/actionpack-2.3.4/lib/action_controller/test_process.rb:398:in `get' > ./spec/controllers/applications_controller_spec.rb:26: > > > Note that this route works fine at runtime in the browser. Also rails is able to resolve the route "edit_account_job_application_path". > > I'm running rspec 1.3.0 and rspec-rails 1.3.2 > > Thanks in advance! > > Matt > > _______________________________________________ > 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 Fri Jul 16 07:33:13 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 16 Jul 2010 06:33:13 -0500 Subject: [rspec-users] Questions about testing a module method that randomly creates stuff from list. In-Reply-To: <12292557.1279214324721.JavaMail.root@wmvirt66> References: <12292557.1279214324721.JavaMail.root@wmvirt66> Message-ID: On Jul 15, 2010, at 12:18 PM, Greg Ditrick wrote: > All, > > I have a method in a shared Module that shuffles data and then output other data. The method is somewhat large (maybe 50 lines) and sometimes calls other sub methods to help to complete the output which must meet a specific criteria or it re-shuffles. This sounds like a long, procedural method. Can it be broken down any further (i.e. delegating more of its work to other methods)? > My questions are: I'll try to answer them, but I don't have much to go on. If you want more specific answers, we'll need to see the method in question. > 1) How do I capture that a sub method is called? Module.should_recieve(:sub_method) ??? I try to avoid message expectations on the same object that I'm spec'ing. That said, here's how you can do it: object = Object.new.extend(MySharedModule) object.should_receive(:sub_method) object.super_method The problem with this approach, especially in light of what sounds like a very complex method, is that the real sub_method is not called, so you have to set up the proper return value: object.should_receive(:sub_method).and_return(:a_value_that_super_method_can_work_with) object.super_method If the real sub_method sets any internal state (i.e. assigns values to instance variables), then this won't work at all. > 2) How do I capture the rand number that caused a condition (like the :sub_method being called, an Error raised, etc.). I know srand will give me the seed that caused it. But, how do I capture it on the failure? For example: > true.should_not be_true || File.open(?capture_rand.out?,?a?) { |f| f.puts ?#{srand}?} > Can you do an || (or) statement like that and have it capture the seed and fail the example? Any ideas? Any other ways of capturing data like that? It's much easier to control state in an example, rather than inspect state and set different expectations based on it. Consider a simulation of a game that involves a die: die = double('die') die.stub(:roll).and_return(2) board.set(piece).at(30) board.roll(die) board.square_at(32).should contain(piece) Make sense? HTH, David > After I capture the seeds, I?m thinking I could than use those seeds to fine tune specific tests. > > > Thanks, > > GregD > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Fri Jul 16 10:17:49 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 16 Jul 2010 09:17:49 -0500 Subject: [rspec-users] shared example groups Message-ID: <3A6CC2A7-FEB3-40D1-BBEB-747882DFAC8F@gmail.com> Hey all, For anyone interested in shared example groups, please read and feel free to comment on http://github.com/rspec/rspec-core/issues/#issue/71. Cheers, David From gditrick at fuse.net Fri Jul 16 12:38:28 2010 From: gditrick at fuse.net (Greg Ditrick) Date: Fri, 16 Jul 2010 12:38:28 -0400 Subject: [rspec-users] Questions about testing a module method that randomly creates stuff from list. Message-ID: <29113393.1279298308506.JavaMail.root@wmvirt44> ---- David Chelimsky wrote: > On Jul 15, 2010, at 12:18 PM, Greg Ditrick wrote: > > > This sounds like a long, procedural method. Can it be broken down any further (i.e. delegating more of its work to other methods)? Yes, it is. The sub methods are the broken down part and not overridden super methods like I guess I made it sound based on your answers below. > I try to avoid message expectations on the same object that I'm spec'ing. That said, here's how you can do it: > > object = Object.new.extend(MySharedModule) > > object.should_receive(:sub_method) > object.super_method > > The problem with this approach, especially in light of what sounds like a very complex method, is that the real sub_method is not called, so you have to set up the proper return value: > > object.should_receive(:sub_method).and_return(:a_value_that_super_method_can_work_with) > object.super_method > > If the real sub_method sets any internal state (i.e. assigns values to instance variables), then this won't work at all. Well, they don't assign instance variables. They are really just methods handling conditions of the randomness in the parent method. > It's much easier to control state in an example, rather than inspect state and set different expectations based on it. Consider a simulation of a game that involves a die: > > die = double('die') > die.stub(:roll).and_return(2) > > board.set(piece).at(30) > board.roll(die) > board.square_at(32).should contain(piece) > > Make sense? Funny you used die when this problem is for a game. Yes, I can stub out the conditions that each child method handles. This procedural method has grown because of the permutations increase exponentially with more data. But, the conditions to handle (defined in the child methods) have become finite and all I have to do is test those with mocks and stubs. I know I put the cart before the horse in TDD/BDD, but this was a very difficult problem to solve: Create a random tournament layout of unique teams of players where a team is matched with another random team of different players and every player plays on teams made up of all the other players to complete the tournament. This way you find the best individual player. Example of this would be euchre, bridge, other team playing card games, etc. But not limited to card games and not limited to 2 man teams. Also, it must allow for uneven number of players in the tournament. i.e. players would have byes throughout the tournament and those byes would be evenly distributed throughout the tournament. For example: a tournament of 2 players per team and 2 teams per match made up of say 15 players would have all players have had the same number of byes at the end of every 5th round. I actually wrote this 20 years ago in ANSI C. Now I have written it in ruby. It has been just about as hard to do, but less lines of code, cleaner and runs faster mainly because in the C code evaluated each team as it was searching for a team to place into a round where is the ruby code it was simple to remove and shrink the possible opponents with one line of code. :) So, while the C code would take maybe hours to figure out a layout of 200+ euchre players. The ruby code does it in a few minutes on the same machine. Not that you would every have that large of a tournament. Just out of curiosity, I tried the a very large size tournament to compare the timing. I do have one more question, how would you write a test for a recursive method? I have a couple of those too. Thanks for the ideas, GregD From dchelimsky at gmail.com Fri Jul 16 20:21:47 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 16 Jul 2010 19:21:47 -0500 Subject: [rspec-users] Questions about testing a module method that randomly creates stuff from list. In-Reply-To: <29113393.1279298308506.JavaMail.root@wmvirt44> References: <29113393.1279298308506.JavaMail.root@wmvirt44> Message-ID: <6EE0296B-3D1B-4212-9DD0-C578FF331FA2@gmail.com> On Jul 16, 2010, at 11:38 AM, Greg Ditrick wrote: > ---- David Chelimsky wrote: >> On Jul 15, 2010, at 12:18 PM, Greg Ditrick wrote: >> >> >> This sounds like a long, procedural method. Can it be broken down any further (i.e. delegating more of its work to other methods)? > > Yes, it is. The sub methods are the broken down part and not overridden super methods like I guess I made it sound based on your answers below. > > >> I try to avoid message expectations on the same object that I'm spec'ing. That said, here's how you can do it: >> >> object = Object.new.extend(MySharedModule) >> >> object.should_receive(:sub_method) >> object.super_method >> >> The problem with this approach, especially in light of what sounds like a very complex method, is that the real sub_method is not called, so you have to set up the proper return value: >> >> object.should_receive(:sub_method).and_return(:a_value_that_super_method_can_work_with) >> object.super_method >> >> If the real sub_method sets any internal state (i.e. assigns values to instance variables), then this won't work at all. > > Well, they don't assign instance variables. They are really just methods handling conditions of the randomness in the parent method. > > >> It's much easier to control state in an example, rather than inspect state and set different expectations based on it. Consider a simulation of a game that involves a die: >> >> die = double('die') >> die.stub(:roll).and_return(2) >> >> board.set(piece).at(30) >> board.roll(die) >> board.square_at(32).should contain(piece) >> >> Make sense? > > Funny you used die when this problem is for a game. > > Yes, I can stub out the conditions that each child method handles. This procedural method has grown because of the permutations increase exponentially with more data. But, the conditions to handle (defined in the child methods) have become finite and all I have to do is test those with mocks and stubs. Sounds like you've got a lot of conditional logic that might be better expressed with polymorphism? I'd need to see the method, but if you expressed the conditions in different objects rather than child methods, you might end up with smaller bits that are easier to test in isolation. > I know I put the cart before the horse in TDD/BDD, but this was a very difficult problem to solve: We all put the cart before the horse from time to time, but your "but" suggests that you believe the TDD is only for easy problems. That couldn't be farther from the truth. The whole point is to start off with a small bit functionality, drive it out with tests, and slowly build up the complexity. > Create a random tournament layout of unique teams of players where a team is matched with another random team of different players and every player plays on teams made up of all the other players to complete the tournament. This way you find the best individual player. Example of this would be euchre, bridge, other team playing card games, etc. But not limited to card games and not limited to 2 man teams. Also, it must allow for uneven number of players in the tournament. i.e. players would have byes throughout the tournament and those byes would be evenly distributed throughout the tournament. For example: a tournament of 2 players per team and 2 teams per match made up of say 15 players would have all players have had the same number of byes at the end of every 5th round. > > I actually wrote this 20 years ago in ANSI C. Now I have written it in ruby. It has been just about as hard to do, but less lines of code, cleaner and runs faster mainly because in the C code evaluated each team as it was searching for a team to place into a round where is the ruby code it was simple to remove and shrink the possible opponents with one line of code. :) So, while the C code would take maybe hours to figure out a layout of 200+ euchre players. The ruby code does it in a few minutes on the same machine. Not that you would every have that large of a tournament. Just out of curiosity, I tried the a very large size tournament to compare the timing. > > I do have one more question, how would you write a test for a recursive method? I have a couple of those too. I've never found a better way than to treat it as a black box and specify how it should respond to different inputs. HTH, David > > Thanks for the ideas, > > GregD From daniel.amselem at gmail.com Sat Jul 17 04:29:55 2010 From: daniel.amselem at gmail.com (Daniel Salmeron Amselem) Date: Sat, 17 Jul 2010 01:29:55 -0700 (PDT) Subject: [rspec-users] assigns and should eql don't work as expected Message-ID: Today I've been writing some tests for a new rails 3 app, but after reading the doc from http://rdoc.info/projects/rspec/rspec-expectations, I still can't understand why the test doesn't work. My setup is: rvm 0.1.41 ruby 1.9.2dev (2010-07-11 revision 28618) [x86_64-darwin10.4.0] -> ruby 1.9.2-rc2 rspec 2.0.0.beta.17 rspec-rails 2.0.0.beta.17 devise 1.1.rc2 This is the test for the controller: require 'spec_helper' describe PeopleController do describe "routes" do it "should route to GET people#new" do {:get => "/people/new"}.should route_to(:controller => "people", :action => "new") end end describe "Methods" do before :each do @member = Factory(:member) sign_in @member @person = @member.build_person end it "should render form for a new person on GET people#new" do @member.should_receive(:build_person).and_return(@person) get :new assigns[:person].should eql(@person) response.should be_success response.should render_template("new") end end end And the controller: class PeopleController < ApplicationController before_filter :authenticate_member! def new @person = current_member.build_person end end When running the test I get: .F................. 1) PeopleController Methods should render form for a new person on GET people#new Failure/Error: assigns[:person].should eql(@person) expected # got # (compared using eql?) # ./spec/controllers/people_controller_spec.rb:24:in `block (3 levels) in ' Finished in 2.29 seconds 19 examples, 1 failure The error with the full backtrace here: http://gist.github.com/479362 Which doesn't seem to make sense. Any ideas? Thanks. From dchelimsky at gmail.com Sat Jul 17 09:09:46 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 17 Jul 2010 08:09:46 -0500 Subject: [rspec-users] assigns and should eql don't work as expected In-Reply-To: References: Message-ID: <1ED32CF6-E1B1-437C-928D-DB4BED75DD04@gmail.com> On Jul 17, 2010, at 3:29 AM, Daniel Salmeron Amselem wrote: > Today I've been writing some tests for a new rails 3 app, but after > reading the doc from http://rdoc.info/projects/rspec/rspec-expectations, > I still can't understand why the test doesn't work. My setup is: > > rvm 0.1.41 > ruby 1.9.2dev (2010-07-11 revision 28618) [x86_64-darwin10.4.0] -> > ruby 1.9.2-rc2 > rspec 2.0.0.beta.17 > rspec-rails 2.0.0.beta.17 > devise 1.1.rc2 > > This is the test for the controller: > > > require 'spec_helper' > > describe PeopleController do > > describe "routes" do > it "should route to GET people#new" do > {:get => "/people/new"}.should route_to(:controller => > "people", :action => "new") > end > end > > describe "Methods" do > > before :each do > @member = Factory(:member) > sign_in @member > @person = @member.build_person > end > > it "should render form for a new person on GET people#new" do > @member.should_receive(:build_person).and_return(@person) > > get :new > > assigns[:person].should eql(@person) > response.should be_success > response.should render_template("new") > end > end > > end > > And the controller: > > class PeopleController < ApplicationController > before_filter :authenticate_member! > > def new > @person = current_member.build_person > end > > end > > When running the test I get: > > > .F................. > > 1) PeopleController Methods should render form for a new person on GET > people#new > Failure/Error: assigns[:person].should eql(@person) > > expected # gender: nil, university: nil, year: nil, email: nil, phone: nil, > house: nil, user_account_id: 126, user_account_type: "Member", > home_town: nil, bio: nil, current_location: nil, high_school: nil, > undergrad: nil, profession: nil, concentration: nil, created_at: nil, > updated_at: nil> > got # gender: nil, university: nil, year: nil, email: nil, phone: nil, > house: nil, user_account_id: 126, user_account_type: "Member", > home_town: nil, bio: nil, current_location: nil, high_school: nil, > undergrad: nil, profession: nil, concentration: nil, created_at: nil, > updated_at: nil> Here's how ActiveRecord defines == (to which it delegates from eql?) http://github.com/rails/rails/blob/c6e20586372743ce200449bf0ac21aed04c6b81e/activerecord/lib/active_record/base.rb#L1536 It returns false if the record has no id (!comparison_object.new_record?), even if all of the other attributes match. In order to get this to pass you have to actually save the object so it has an id, not just build it. I discussed this with Rails core members a year or two ago and while they agreed this would make testing easier, there were two motivating arguments not to change it: a) conceptually, id-less records are not necessarily the same entity (this one is a bit fuzzy to me) and b) it's a risky change given the amount of rails code in existence. The other thing you can do is skip the stubbing and just say: assigns(:person).should be_a_new(Person) You could also write a custom matcher - something like match_new_record(other) that compares all of the attributes. Maybe it's have_same_attributes_as: assigns(:person).should have_same_attributes_as(@person) I'd consider adding that to rspec-rails. Might be good to have a matcher with docs that explain all this to help avoid this sort of confusion in the future. WDYT?, David > > (compared using eql?) > # ./spec/controllers/people_controller_spec.rb:24:in `block (3 > levels) in ' > > > Finished in 2.29 seconds > 19 examples, 1 failure > > The error with the full backtrace here: http://gist.github.com/479362 > > Which doesn't seem to make sense. Any ideas? > > Thanks. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Sat Jul 17 09:41:37 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 17 Jul 2010 08:41:37 -0500 Subject: [rspec-users] assigns and should eql don't work as expected In-Reply-To: <1ED32CF6-E1B1-437C-928D-DB4BED75DD04@gmail.com> References: <1ED32CF6-E1B1-437C-928D-DB4BED75DD04@gmail.com> Message-ID: On Jul 17, 2010, at 8:09 AM, David Chelimsky wrote: > > On Jul 17, 2010, at 3:29 AM, Daniel Salmeron Amselem wrote: > >> Today I've been writing some tests for a new rails 3 app, but after >> reading the doc from http://rdoc.info/projects/rspec/rspec-expectations, >> I still can't understand why the test doesn't work. My setup is: >> >> rvm 0.1.41 >> ruby 1.9.2dev (2010-07-11 revision 28618) [x86_64-darwin10.4.0] -> >> ruby 1.9.2-rc2 >> rspec 2.0.0.beta.17 >> rspec-rails 2.0.0.beta.17 >> devise 1.1.rc2 >> >> This is the test for the controller: >> >> >> require 'spec_helper' >> >> describe PeopleController do >> >> describe "routes" do >> it "should route to GET people#new" do >> {:get => "/people/new"}.should route_to(:controller => >> "people", :action => "new") >> end >> end >> >> describe "Methods" do >> >> before :each do >> @member = Factory(:member) >> sign_in @member >> @person = @member.build_person >> end >> >> it "should render form for a new person on GET people#new" do >> @member.should_receive(:build_person).and_return(@person) >> >> get :new >> >> assigns[:person].should eql(@person) >> response.should be_success >> response.should render_template("new") >> end >> end >> >> end >> >> And the controller: >> >> class PeopleController < ApplicationController >> before_filter :authenticate_member! >> >> def new >> @person = current_member.build_person >> end >> >> end >> >> When running the test I get: >> >> >> .F................. >> >> 1) PeopleController Methods should render form for a new person on GET >> people#new >> Failure/Error: assigns[:person].should eql(@person) >> >> expected #> gender: nil, university: nil, year: nil, email: nil, phone: nil, >> house: nil, user_account_id: 126, user_account_type: "Member", >> home_town: nil, bio: nil, current_location: nil, high_school: nil, >> undergrad: nil, profession: nil, concentration: nil, created_at: nil, >> updated_at: nil> >> got #> gender: nil, university: nil, year: nil, email: nil, phone: nil, >> house: nil, user_account_id: 126, user_account_type: "Member", >> home_town: nil, bio: nil, current_location: nil, high_school: nil, >> undergrad: nil, profession: nil, concentration: nil, created_at: nil, >> updated_at: nil> > > Here's how ActiveRecord defines == (to which it delegates from eql?) > > http://github.com/rails/rails/blob/c6e20586372743ce200449bf0ac21aed04c6b81e/activerecord/lib/active_record/base.rb#L1536 > > It returns false if the record has no id (!comparison_object.new_record?), even if all of the other attributes match. In order to get this to pass you have to actually save the object so it has an id, not just build it. > > I discussed this with Rails core members a year or two ago and while they agreed this would make testing easier, there were two motivating arguments not to change it: a) conceptually, id-less records are not necessarily the same entity (this one is a bit fuzzy to me) and b) it's a risky change given the amount of rails code in existence. > > The other thing you can do is skip the stubbing and just say: > > assigns(:person).should be_a_new(Person) > > You could also write a custom matcher - something like match_new_record(other) that compares all of the attributes. Maybe it's have_same_attributes_as: > > assigns(:person).should have_same_attributes_as(@person) > > I'd consider adding that to rspec-rails. Might be good to have a matcher with docs that explain all this to help avoid this sort of confusion in the future. Another option would be to add something like this: RSpec.configure do |c| c.treat_new_active_record_objects_as_equal end ... and have that override ==(other) on ActiveRecord::Base. It's invasive, but you have to take an action to do the override. WDYT? > > WDYT?, > David > > >> >> (compared using eql?) >> # ./spec/controllers/people_controller_spec.rb:24:in `block (3 >> levels) in ' >> >> >> Finished in 2.29 seconds >> 19 examples, 1 failure >> >> The error with the full backtrace here: http://gist.github.com/479362 >> >> Which doesn't seem to make sense. Any ideas? >> >> Thanks. >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users > From biot023 at gmail.com Sat Jul 17 11:37:46 2010 From: biot023 at gmail.com (doug livesey) Date: Sat, 17 Jul 2010 16:37:46 +0100 Subject: [rspec-users] How are people speccing Rails 3 ActiveRecord queries? Message-ID: Hi -- how are people speccing Rails 3 ActiveRecord queries? At the minute I'm chaining a load of should_receive calls on mock relation objects, but can't help thinking that there must be a more elegant way of going about it. Is there a best practice for this, yet? Cheers, Doug. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Sat Jul 17 12:11:01 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 17 Jul 2010 11:11:01 -0500 Subject: [rspec-users] How are people speccing Rails 3 ActiveRecord queries? In-Reply-To: References: Message-ID: <35B93259-0426-484C-A1BA-79DBECCDCABA@gmail.com> On Jul 17, 2010, at 10:37 AM, doug livesey wrote: > Hi -- how are people speccing Rails 3 ActiveRecord queries? > At the minute I'm chaining a load of should_receive calls on mock relation objects, but can't help thinking that there must be a more elegant way of going about it. > Is there a best practice for this, yet? For me, there is only one best practice: think. Everything else is a guideline in some context. That said, here are some of my guidelines, in context. YMMV. My approach to spec'ing models is different from that for controllers and views. In controller and view specs I prefer to stub out the data layer most of the time because I don't want the controller/view specs failing due to things like validations, which are model concerns. Spec'ing models is a different animal. I'll still use stubs where they make sense, but I'm perfectly happy using real objects and interacting with the database when spec'ing behavior that is influenced by the db and relationships between models. I prefer to think of spec'ing behavior rather than spec'ing query details. A simple example would be querying for the "active" members of a group. We could say: Member.should_receive(:where).with(:active => true) Member.active Or, we could say: active_member = Factory(:member, :active => true) inactive_member = Factory(:member, :active => false) Member.active.should eq([active_member]) I, personally, find the latter more expressive, and we don't have to worry about the details of AR in the specs. HTH, David > Cheers, > Doug. From biot023 at gmail.com Sat Jul 17 12:43:19 2010 From: biot023 at gmail.com (doug livesey) Date: Sat, 17 Jul 2010 17:43:19 +0100 Subject: [rspec-users] How are people speccing and cuke-ing Paperclip (with S3)? Message-ID: Hi -- I'm running into all sorts of difficulties trying to use paperclip with cucumber and rspec. Basically, I'm stubbing out paperclip calls with WebMock (I've adapted the shoulda macro that uses FakeWeb to do this). But every time I get things running smoothly, something else pops up to screw things up. The latest is a "Too many open files" error. So how are other people speccing their paperclip code? Please tell me they're doing *some*thing, as I'm using S3 storage, which would really slow my tests down if I just did nothing. I'm starting to think of all sorts of horrible solutions, like making the storage strategy dependent on the environment, like using the file system if it is a test or cucumber env. But I'd hate to resort to that. Any & all advice really appreciated! Cheers, Doug. PS -- cross-posted at rspec and paperclip lists. -------------- next part -------------- An HTML attachment was scrubbed... URL: From biot023 at gmail.com Sat Jul 17 12:47:45 2010 From: biot023 at gmail.com (doug livesey) Date: Sat, 17 Jul 2010 17:47:45 +0100 Subject: [rspec-users] How are people speccing Rails 3 ActiveRecord queries? In-Reply-To: <35B93259-0426-484C-A1BA-79DBECCDCABA@gmail.com> References: <35B93259-0426-484C-A1BA-79DBECCDCABA@gmail.com> Message-ID: Interesting. I'll give that a bash, too. I must admit, I tend to use the first approach, but the second seems a little more true to the spirit of testing. I can imagine that it might get rather involved when setting up the database for even half-way complex queries, though. I'll see how I get on with approach no. 2 for a while. Thanks, Doug. On 17 July 2010 17:11, David Chelimsky wrote: > On Jul 17, 2010, at 10:37 AM, doug livesey wrote: > > > Hi -- how are people speccing Rails 3 ActiveRecord queries? > > At the minute I'm chaining a load of should_receive calls on mock > relation objects, but can't help thinking that there must be a more elegant > way of going about it. > > Is there a best practice for this, yet? > > For me, there is only one best practice: think. Everything else is a > guideline in some context. > > That said, here are some of my guidelines, in context. YMMV. > > My approach to spec'ing models is different from that for controllers and > views. In controller and view specs I prefer to stub out the data layer most > of the time because I don't want the controller/view specs failing due to > things like validations, which are model concerns. > > Spec'ing models is a different animal. I'll still use stubs where they make > sense, but I'm perfectly happy using real objects and interacting with the > database when spec'ing behavior that is influenced by the db and > relationships between models. > > I prefer to think of spec'ing behavior rather than spec'ing query details. > A simple example would be querying for the "active" members of a group. We > could say: > > Member.should_receive(:where).with(:active => true) > Member.active > > Or, we could say: > > active_member = Factory(:member, :active => true) > inactive_member = Factory(:member, :active => false) > Member.active.should eq([active_member]) > > I, personally, find the latter more expressive, and we don't have to worry > about the details of AR in the specs. > > HTH, > David > > > Cheers, > > Doug. > > _______________________________________________ > 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 steve at steveklabnik.com Sat Jul 17 12:58:14 2010 From: steve at steveklabnik.com (Steve Klabnik) Date: Sat, 17 Jul 2010 12:58:14 -0400 Subject: [rspec-users] How are people speccing and cuke-ing Paperclip (with S3)? In-Reply-To: References: Message-ID: One of the things that you learn after testing for a while is "what to test." You don't need to test Paperclip's ability to put files to S3; that's what Paperclip's internal tests are for. So what I do is this: http://gist.github.com/479647 When I'm developing locally or testing, I just write files to my local machine. On production, they go to S3. -------------- next part -------------- An HTML attachment was scrubbed... URL: From win at wincent.com Sat Jul 17 12:03:19 2010 From: win at wincent.com (Wincent Colaiuta) Date: Sat, 17 Jul 2010 18:03:19 +0200 Subject: [rspec-users] How are people speccing Rails 3 ActiveRecord queries? In-Reply-To: References: Message-ID: <255E7690-22BD-4B9D-9D41-C46A7E53DF3D@wincent.com> El 17/07/2010, a las 17:37, doug livesey escribi?: > Hi -- how are people speccing Rails 3 ActiveRecord queries? > At the minute I'm chaining a load of should_receive calls on mock relation > objects, but can't help thinking that there must be a more elegant way of > going about it. > Is there a best practice for this, yet? I'm pushing them down into the model where possible and testing the model as a black box. Cheers, Wincent From biot023 at gmail.com Sat Jul 17 13:32:23 2010 From: biot023 at gmail.com (doug livesey) Date: Sat, 17 Jul 2010 18:32:23 +0100 Subject: [rspec-users] How are people speccing and cuke-ing Paperclip (with S3)? In-Reply-To: References: Message-ID: I was wary of taking an approach like that, as it feels a little like test code bleeding into production code, but the sheer number of problems I'm having trying another way tells me that I'm very inadvisedly swimming against the stream, here. So I think I'll rethink my strategy & try something more like this -- thanks! Doug. On 17 July 2010 17:58, Steve Klabnik wrote: > One of the things that you learn after testing for a while is "what to > test." You don't need to test Paperclip's ability to put files to S3; that's > what Paperclip's internal tests are for. So what I do is this: > > http://gist.github.com/479647 > > When I'm developing locally or testing, I just write files to my local > machine. On production, they go to S3. > > _______________________________________________ > 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 ashley.moran at patchspace.co.uk Sat Jul 17 13:41:08 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sat, 17 Jul 2010 18:41:08 +0100 Subject: [rspec-users] How are people speccing Rails 3 ActiveRecord queries? In-Reply-To: References: Message-ID: On 17 Jul 2010, at 4:37 PM, doug livesey wrote: > At the minute I'm chaining a load of should_receive calls on mock relation objects I've found this can cause pain in so many ways: * Your tests end up coupled to the database structure (as that's how most associations are inferred) * You're at the mercy of the implementation of the association proxy (I've found this more problematic with DataMapper, whose associations haven't always behaved quite how I expected them to...) * You can easily end up with a lot of setup duplication I've had enough pain from this that I now refuse to mock *any* ActiveRecord (the library or the pattern) code. It's arguably a violation of Don't Mock Types You Don't Own anyway. HTH Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From ashley.moran at patchspace.co.uk Sat Jul 17 13:46:47 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sat, 17 Jul 2010 18:46:47 +0100 Subject: [rspec-users] How are people speccing and cuke-ing Paperclip (with S3)? In-Reply-To: References: Message-ID: On 17 Jul 2010, at 5:58 PM, Steve Klabnik wrote: > You don't need to test Paperclip's ability to put files to S3 It depends on your confidence in Paperclip (s/Paperclip/X random library) and the severity of problem it could cause if it doesn't work. To me, at least, it's more a risk/value judgement than a binary decision. If millions of pounds rested on Paperclip uploading files to the right place, I'd test the hell out of it before using it in my own app! Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From ashley.moran at patchspace.co.uk Sat Jul 17 13:52:45 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sat, 17 Jul 2010 18:52:45 +0100 Subject: [rspec-users] How are people speccing and cuke-ing Paperclip (with S3)? In-Reply-To: References: Message-ID: On 17 Jul 2010, at 5:43 PM, doug livesey wrote: > Please tell me they're doing *some*thing, as I'm using S3 storage, which would really slow my tests down if I just did nothing. > I'm starting to think of all sorts of horrible solutions, like making the storage strategy dependent on the environment, like using the file system if it is a test or cucumber env. For absolute confidence, you can use S3 for a full integration test. You only need one of these for each type of interaction with S3 though. For faster local integration tests, you could write a mock implementation of S3. I've not used Paperclip, but it looks like it works as a DSL embedded into ActiveRecord class definitions. That'll make it a lot harder to separate out the file handling that if you were writing it out explicitly. Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From costa at mouldwarp.com Sat Jul 17 14:18:23 2010 From: costa at mouldwarp.com (Costa Shapiro) Date: Sat, 17 Jul 2010 14:18:23 -0400 Subject: [rspec-users] Data-wise context combination for controller speccing Message-ID: Hello, I've been thinking of how to express my idea in code, but since I've never been involved in RSpec development, I'd better have some feedback here first. The feature suggestion below applies to any controller-like code under spec, i.e. a stateless module producing output or just altering its data store (it doesn't necessarily have to be a C of the MVC, but I suppose merb/rails developers will particularly appreciate it). Here is a skimmed sample to illustrate the pain: describe BookController do context "registering a book" do specify "from a new author on a new subject" do auth = mock(:name => 'John Doe') Author.should_receive(:find_ by_name).and_return(nil) Author.should_receive(:new).and_return(auth) auth.should_receive(:save).and_return(true) subj = mock(:short => 'Mockery') Subject.should_receive(:find_by_short).and_return(nil) Subject.should_receive(:new).and_return(subj) subj.should_receive(:save).and_return(true) title = 'Specs on Steroids' book = mock Book.should_receive(:new).and_return(book) book.should_receive(:save).and_return(true) post :register :author => auth.name, :title => title, :subject => subj.short response.should be_success end specify "from a known author on a new subject" do auth = mock(:name => 'Joe Dohn') Author.should_receive(:find_by_name).and_return(auth) subj = mock(:short => 'Mockery') Subject.should_receive(:find_by_short).and_return(nil) Subject.should_receive(:new).and_return(subj) subj.should_receive(:save).and_return(true) title = 'Specs on Steroids II' book = mock Book.should_receive(:new).and_return(book) book.should_receive(:save).and_return(true) post :register :author => auth.name, :title => title, :subject => subj.short response.should be_success end specify "from a known author on a known subject" do auth = mock(:name => 'Joe Dohn') Author.should_receive(:find_by_name).and_return(auth) subj = mock(:short => 'Forgery') Subject.should_receive(:find_by_short).and_return(subj) #... end specify "from a new author on a known subject" do #... end end end And this is what I have in mind for doing exactly the same job: describe BookController do context "registering a book" do before :any, "from a new author", :author do @auth = mock(:name => 'John Doe') Author.should_receive(:find_by_name).and_return(nil) Author.should_receive(:new).and_return(@auth) @auth.should_receive(:save).and_return(true) end before :any, "from a known author", :author do @auth = mock(:name => 'Joe Dohn') Author.should_receive(:find_by_name).and_return(@auth) end before :any, "on a new subject", :subject do @subj = mock(:short => 'Mockery') Subject.should_receive(:find_by_short).and_return(nil) Subject.should_receive(:new).and_return(@subj) @subj.should_receive(:save).and_return(true) end before :any, "on a known subject", :subject do @subj = mock(:name => 'Joe Dohn') Subject.should_receive(:find_by_name).and_return(@subj) end it "should succeed", :with => [:author, :subject] do title = 'Specs on Steroids X' post :register :author => @auth.name, :title => title, :subject => @subj.short response.should be_success end end end A run of such specs will effectively multiply the tests ? automatically ? choosing before and after blocks as specified. I'm sorry, I haven't thought the DSL through, but I hope the main idea can be seen: contexts do not have to be hierarchical. In my opinion, adding some sort of context selection+combination capabilities (AOP-style) will contribute greatly to the expressiveness of the spec language. Thank you for your attention, Costa. -------------- next part -------------- An HTML attachment was scrubbed... URL: From daniel.amselem at gmail.com Sat Jul 17 15:25:30 2010 From: daniel.amselem at gmail.com (Daniel Salmeron Amselem) Date: Sat, 17 Jul 2010 12:25:30 -0700 (PDT) Subject: [rspec-users] assigns and should eql don't work as expected In-Reply-To: References: <1ED32CF6-E1B1-437C-928D-DB4BED75DD04@gmail.com> Message-ID: Thanks David, this was driving me crazy. In my opinion, I think will be a great idea to add a new matcher to rspec-rails to do this kind of comparison better than overriding == , and have total control of what you want to test in each case. Anyways, thanks for helping me on this. On Jul 17, 9:41?am, David Chelimsky wrote: > On Jul 17, 2010, at 8:09 AM, David Chelimsky wrote: > > > > > > > > > On Jul 17, 2010, at 3:29 AM, Daniel Salmeron Amselem wrote: > > >> Today I've been writing some tests for a new rails 3 app, but after > >> reading the doc fromhttp://rdoc.info/projects/rspec/rspec-expectations, > >> I still can't understand why the test doesn't work. My setup is: > > >> rvm 0.1.41 > >> ruby 1.9.2dev (2010-07-11 revision 28618) [x86_64-darwin10.4.0] -> > >> ruby 1.9.2-rc2 > >> rspec 2.0.0.beta.17 > >> rspec-rails 2.0.0.beta.17 > >> devise 1.1.rc2 > > >> This is the test for the controller: > > >> require 'spec_helper' > > >> describe PeopleController do > > >> describe "routes" do > >> ? it "should route to GET people#new" do > >> ? ? {:get => "/people/new"}.should route_to(:controller => > >> "people", :action => "new") > >> ? end > >> end > > >> describe "Methods" do > > >> ? before :each do > >> ? ? @member = Factory(:member) > >> ? ? sign_in @member > >> ? ? @person = @member.build_person > >> ? end > > >> ? it "should render form for a new person on GET people#new" do > >> ? ? @member.should_receive(:build_person).and_return(@person) > > >> ? ? get :new > > >> ? ? assigns[:person].should eql(@person) > >> ? ? response.should be_success > >> ? ? response.should render_template("new") > >> ? end > >> end > > >> end > > >> And the controller: > > >> class PeopleController < ApplicationController > >> before_filter :authenticate_member! > > >> def new > >> ? @person = current_member.build_person > >> end > > >> end > > >> When running the test I get: > > >> .F................. > > >> 1) PeopleController Methods should render form for a new person on GET > >> people#new > >> ? Failure/Error: assigns[:person].should eql(@person) > > >> ? expected # >> gender: nil, university: nil, year: nil, email: nil, phone: nil, > >> house: nil, user_account_id: 126, user_account_type: "Member", > >> home_town: nil, bio: nil, current_location: nil, high_school: nil, > >> undergrad: nil, profession: nil, concentration: nil, created_at: nil, > >> updated_at: nil> > >> ? ? ? ?got # >> gender: nil, university: nil, year: nil, email: nil, phone: nil, > >> house: nil, user_account_id: 126, user_account_type: "Member", > >> home_town: nil, bio: nil, current_location: nil, high_school: nil, > >> undergrad: nil, profession: nil, concentration: nil, created_at: nil, > >> updated_at: nil> > > > Here's how ActiveRecord defines == (to which it delegates from eql?) > > >http://github.com/rails/rails/blob/c6e20586372743ce200449bf0ac21aed04... > > > It returns false if the record has no id (!comparison_object.new_record?), even if all of the other attributes match. In order to get this to pass you have to actually save the object so it has an id, not just build it. > > > I discussed this with Rails core members a year or two ago and while they agreed this would make testing easier, there were two motivating arguments not to change it: a) conceptually, id-less records are not necessarily the same entity (this one is a bit fuzzy to me) and b) it's a risky change given the amount of rails code in existence. > > > The other thing you can do is skip the stubbing and just say: > > > ?assigns(:person).should be_a_new(Person) > > > You could also write a custom matcher - something like match_new_record(other) that compares all of the attributes. Maybe it's have_same_attributes_as: > > > ?assigns(:person).should have_same_attributes_as(@person) > > > I'd consider adding that to rspec-rails. Might be good to have a matcher with docs that explain all this to help avoid this sort of confusion in the future. > > Another option would be to add something like this: > > RSpec.configure do |c| > ? c.treat_new_active_record_objects_as_equal > end > > ... and have that override ==(other) on ActiveRecord::Base. It's invasive, but you have to take an action to do the override. > > WDYT? > > > > > > > > > WDYT?, > > David > > >> ? (compared using eql?) > >> ? # ./spec/controllers/people_controller_spec.rb:24:in `block (3 > >> levels) in ' > > >> Finished in 2.29 seconds > >> 19 examples, 1 failure > > >> The error with the full backtrace here:http://gist.github.com/479362 > > >> Which doesn't seem to make sense. Any ideas? > > >> Thanks. > >> _______________________________________________ > >> rspec-users mailing list > >> rspec-us... at rubyforge.org > >>http://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Sat Jul 17 17:53:47 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 17 Jul 2010 16:53:47 -0500 Subject: [rspec-users] assigns and should eql don't work as expected In-Reply-To: References: <1ED32CF6-E1B1-437C-928D-DB4BED75DD04@gmail.com> Message-ID: On Jul 17, 2010, at 2:25 PM, Daniel Salmeron Amselem wrote: > On Jul 17, 9:41 am, David Chelimsky wrote: >> On Jul 17, 2010, at 8:09 AM, David Chelimsky wrote: >>> On Jul 17, 2010, at 3:29 AM, Daniel Salmeron Amselem wrote: >> >>>> Today I've been writing some tests for a new rails 3 app, but after >>>> reading the doc fromhttp://rdoc.info/projects/rspec/rspec-expectations, >>>> I still can't understand why the test doesn't work. My setup is: >> >>>> rvm 0.1.41 >>>> ruby 1.9.2dev (2010-07-11 revision 28618) [x86_64-darwin10.4.0] -> >>>> ruby 1.9.2-rc2 >>>> rspec 2.0.0.beta.17 >>>> rspec-rails 2.0.0.beta.17 >>>> devise 1.1.rc2 >> >>>> This is the test for the controller: >> >>>> require 'spec_helper' >> >>>> describe PeopleController do >> >>>> describe "routes" do >>>> it "should route to GET people#new" do >>>> {:get => "/people/new"}.should route_to(:controller => >>>> "people", :action => "new") >>>> end >>>> end >> >>>> describe "Methods" do >> >>>> before :each do >>>> @member = Factory(:member) >>>> sign_in @member >>>> @person = @member.build_person >>>> end >> >>>> it "should render form for a new person on GET people#new" do >>>> @member.should_receive(:build_person).and_return(@person) >> >>>> get :new >> >>>> assigns[:person].should eql(@person) >>>> response.should be_success >>>> response.should render_template("new") >>>> end >>>> end >> >>>> end >> >>>> And the controller: >> >>>> class PeopleController < ApplicationController >>>> before_filter :authenticate_member! >> >>>> def new >>>> @person = current_member.build_person >>>> end >> >>>> end >> >>>> When running the test I get: >> >>>> .F................. >> >>>> 1) PeopleController Methods should render form for a new person on GET >>>> people#new >>>> Failure/Error: assigns[:person].should eql(@person) >> >>>> expected #>>> gender: nil, university: nil, year: nil, email: nil, phone: nil, >>>> house: nil, user_account_id: 126, user_account_type: "Member", >>>> home_town: nil, bio: nil, current_location: nil, high_school: nil, >>>> undergrad: nil, profession: nil, concentration: nil, created_at: nil, >>>> updated_at: nil> >>>> got #>>> gender: nil, university: nil, year: nil, email: nil, phone: nil, >>>> house: nil, user_account_id: 126, user_account_type: "Member", >>>> home_town: nil, bio: nil, current_location: nil, high_school: nil, >>>> undergrad: nil, profession: nil, concentration: nil, created_at: nil, >>>> updated_at: nil> >> >>> Here's how ActiveRecord defines == (to which it delegates from eql?) >> >>> http://github.com/rails/rails/blob/c6e20586372743ce200449bf0ac21aed04... >> >>> It returns false if the record has no id (!comparison_object.new_record?), even if all of the other attributes match. In order to get this to pass you have to actually save the object so it has an id, not just build it. >> >>> I discussed this with Rails core members a year or two ago and while they agreed this would make testing easier, there were two motivating arguments not to change it: a) conceptually, id-less records are not necessarily the same entity (this one is a bit fuzzy to me) and b) it's a risky change given the amount of rails code in existence. >> >>> The other thing you can do is skip the stubbing and just say: >> >>> assigns(:person).should be_a_new(Person) >> >>> You could also write a custom matcher - something like match_new_record(other) that compares all of the attributes. Maybe it's have_same_attributes_as: >> >>> assigns(:person).should have_same_attributes_as(@person) >> >>> I'd consider adding that to rspec-rails. Might be good to have a matcher with docs that explain all this to help avoid this sort of confusion in the future. >> >> Another option would be to add something like this: >> >> RSpec.configure do |c| >> c.treat_new_active_record_objects_as_equal >> end >> >> ... and have that override ==(other) on ActiveRecord::Base. It's invasive, but you have to take an action to do the override. >> >> WDYT? > Thanks David, this was driving me crazy. In my opinion, I think will > be a great idea to add a new matcher to rspec-rails to do this kind of > comparison better than overriding == , and have total control of what > you want to test in each case. Anyways, thanks for helping me on this. I added an issue for this: http://github.com/rspec/rspec-rails/issues/#issue/131 Please share ideas there about what this matcher might look like. Cheers, David >>> WDYT?, >>> David >> >>>> (compared using eql?) >>>> # ./spec/controllers/people_controller_spec.rb:24:in `block (3 >>>> levels) in ' >> >>>> Finished in 2.29 seconds >>>> 19 examples, 1 failure >> >>>> The error with the full backtrace here:http://gist.github.com/479362 >> >>>> Which doesn't seem to make sense. Any ideas? >> >>>> Thanks. From dchelimsky at gmail.com Sat Jul 17 19:10:50 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 17 Jul 2010 18:10:50 -0500 Subject: [rspec-users] Data-wise context combination for controller speccing In-Reply-To: References: Message-ID: On Jul 17, 2010, at 1:18 PM, Costa Shapiro wrote: > Hello, > > I've been thinking of how to express my idea in code, but since I've never been involved in RSpec development, I'd better have some feedback here first. > The feature suggestion below applies to any controller-like code under spec, i.e. a stateless module producing output or just altering its data store (it doesn't necessarily have to be a C of the MVC, but I suppose merb/rails developers will particularly appreciate it). > > Here is a skimmed sample to illustrate the pain: > > describe BookController do > > context "registering a book" do > > specify "from a new author on a new subject" do > auth = mock(:name => 'John Doe') > Author.should_receive(:find_ > by_name).and_return(nil) > Author.should_receive(:new).and_return(auth) > auth.should_receive(:save).and_return(true) > > subj = mock(:short => 'Mockery') > Subject.should_receive(:find_by_short).and_return(nil) > Subject.should_receive(:new).and_return(subj) > subj.should_receive(:save).and_return(true) > > title = 'Specs on Steroids' > > book = mock > Book.should_receive(:new).and_return(book) > book.should_receive(:save).and_return(true) > > post :register :author => auth.name, :title => title, :subject => subj.short > response.should be_success > end > > specify "from a known author on a new subject" do > auth = mock(:name => 'Joe Dohn') > Author.should_receive(:find_by_name).and_return(auth) > > subj = mock(:short => 'Mockery') > Subject.should_receive(:find_by_short).and_return(nil) > Subject.should_receive(:new).and_return(subj) > subj.should_receive(:save).and_return(true) > > title = 'Specs on Steroids II' > > book = mock > Book.should_receive(:new).and_return(book) > book.should_receive(:save).and_return(true) > > post :register :author => auth.name, :title => title, :subject => subj.short > response.should be_success > end > > specify "from a known author on a known subject" do > auth = mock(:name => 'Joe Dohn') > Author.should_receive(:find_by_name).and_return(auth) > > subj = mock(:short => 'Forgery') > Subject.should_receive(:find_by_short).and_return(subj) > > #... > end > > specify "from a new author on a known subject" do > #... > end > end > end > > > And this is what I have in mind for doing exactly the same job: > > describe BookController do > > context "registering a book" do > > before :any, "from a new author", :author do > @auth = mock(:name => 'John Doe') > Author.should_receive(:find_by_name).and_return(nil) > Author.should_receive(:new).and_return(@auth) > @auth.should_receive(:save).and_return(true) > end > > before :any, "from a known author", :author do > @auth = mock(:name => 'Joe Dohn') > Author.should_receive(:find_by_name).and_return(@auth) > end > > before :any, "on a new subject", :subject do > @subj = mock(:short => 'Mockery') > Subject.should_receive(:find_by_short).and_return(nil) > Subject.should_receive(:new).and_return(@subj) > @subj.should_receive(:save).and_return(true) > end > > before :any, "on a known subject", :subject do > @subj = mock(:name => 'Joe Dohn') > Subject.should_receive(:find_by_name).and_return(@subj) > end > > it "should succeed", :with => [:author, :subject] do > title = 'Specs on Steroids X' > > post :register :author => @auth.name, :title => title, :subject => @subj.short > response.should be_success > end > end > end > > A run of such specs will effectively multiply the tests ? automatically ? choosing before and after blocks as specified. > I'm sorry, I haven't thought the DSL through, but I hope the main idea can be seen: contexts do not have to be hierarchical. > In my opinion, adding some sort of context selection+combination capabilities (AOP-style) will contribute greatly to the expressiveness of the spec language. I think the idea of mixing/matching sub-contexts is very interesting, but it definitely needs from fleshing out. It would have to be easy to read/understand in the spec file as well as the output. Also, this only works if every combination should behave the same way. I think we'd need a means of saying "given these combinations of data, expect these outcomes". Anybody else have thoughts on this? Cheers, David > Thank you for your attention, > Costa. -------------- next part -------------- An HTML attachment was scrubbed... URL: From elc at mingins.com Sun Jul 18 20:32:57 2010 From: elc at mingins.com (Shane Mingins) Date: Mon, 19 Jul 2010 12:32:57 +1200 Subject: [rspec-users] Gem conflict with RSpec::Rails and Sunspot Message-ID: Hi All I was wondering if someone could perhaps point me to where in RSpec::Rails is the Rails ActionController being subclassed by an Object instance? My ruby-fu is not high enough to work out what's really going on with RSpec::Rails with this. The problem I am having (and I have a code example in the github link below if you want to see, just clone and run rake spec) is that Sunspot is adding an after filter to already loaded subclasses of ActionController::Base. loaded_controllers = [base].concat(base.subclasses.map { |subclass| subclass.constantize }) But that map is returning: ["ActionView::TestCase::TestController", "ApplicationController", "#", "Spec::Rails::Example::ViewExampleGroupController", "Spec::Rails::Example::HelperExampleGroupController"] So I am trying to find what # is and where it's subclassing ActionController. If I comment out config.gem "rspec-rails" in the environment.rb the problem goes away, but that is not a solution as I have boiled this issue down to what I have here from a project that is actually using bundler and so these gems are being specified and required. As I do not know what in RSpec::Rails is actually causing the issue I cannot raise this as an issue with Sunspot with an example of possibly what they should be excluding in their code, if that is the solution to move to. So if anyone could help me out in any way?? I'm happy to do more "leg work" if you could give me some pointers. Cheers Shane git repo showing issue: http://github.com/smingins/rspec-sunspot-conflict using ruby 1.8.7 ruby -v ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] -------------- next part -------------- An HTML attachment was scrubbed... URL: From elc at mingins.com Sun Jul 18 21:21:59 2010 From: elc at mingins.com (Shane Mingins) Date: Mon, 19 Jul 2010 13:21:59 +1200 Subject: [rspec-users] Gem conflict with RSpec::Rails and Sunspot In-Reply-To: References: Message-ID: Seems to be related to the line 'tests Class.new(ActionController::Base)' module Spec module Rails module Example class RoutingExampleGroup < ActionController::TestCase tests Class.new(ActionController::Base) Spec::Example::ExampleGroupFactory.register(:routing, self) end end end end On 19 July 2010 12:32, Shane Mingins wrote: > Hi All > > I was wondering if someone could perhaps point me to where in RSpec::Rails > is the Rails ActionController being subclassed by an Object instance? My > ruby-fu is not high enough to work out what's really going on with > RSpec::Rails with this. > > The problem I am having (and I have a code example in the github link below > if you want to see, just clone and run rake spec) is that Sunspot is adding > an after filter to already loaded subclasses of ActionController::Base. > > loaded_controllers = > [base].concat(base.subclasses.map { |subclass| > subclass.constantize }) > > But that map is returning: > > ["ActionView::TestCase::TestController", "ApplicationController", > "#", > "Spec::Rails::Example::ViewExampleGroupController", > "Spec::Rails::Example::HelperExampleGroupController"] > > So I am trying to find what # is and where it's > subclassing ActionController. > > If I comment out config.gem "rspec-rails" in the environment.rb the problem > goes away, but that is not a solution as I have boiled this issue down to > what I have here from a project that is actually using bundler and so these > gems are being specified and required. > > As I do not know what in RSpec::Rails is actually causing the issue I > cannot raise this as an issue with Sunspot with an example of possibly what > they should be excluding in their code, if that is the solution to move to. > > So if anyone could help me out in any way?? I'm happy to do more "leg > work" if you could give me some pointers. > > Cheers > Shane > > > git repo showing issue: > http://github.com/smingins/rspec-sunspot-conflict > > using ruby 1.8.7 > ruby -v > ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] > -------------- next part -------------- An HTML attachment was scrubbed... URL: From elc at mingins.com Sun Jul 18 21:29:23 2010 From: elc at mingins.com (Shane Mingins) Date: Mon, 19 Jul 2010 13:29:23 +1200 Subject: [rspec-users] Gem conflict with RSpec::Rails and Sunspot In-Reply-To: References: Message-ID: And so ... # Sets the controller class name. Useful if the name can't be inferred from test class. # Expects +controller_class+ as a constant. Example: tests WidgetController. def tests(controller_class) self.controller_class = controller_class end But RoutingExampleGroup is: tests Class.new(ActionController::Base) Seems it's being called incorrectly from RoutingExampleGroup, is that right? On 19 July 2010 13:21, Shane Mingins wrote: > Seems to be related to the line 'tests Class.new(ActionController::Base)' > > module Spec > module Rails > module Example > > class RoutingExampleGroup < ActionController::TestCase > tests Class.new(ActionController::Base) > > Spec::Example::ExampleGroupFactory.register(:routing, self) > end > > end > end > end > > On 19 July 2010 12:32, Shane Mingins wrote: > >> Hi All >> >> I was wondering if someone could perhaps point me to where in RSpec::Rails >> is the Rails ActionController being subclassed by an Object instance? My >> ruby-fu is not high enough to work out what's really going on with >> RSpec::Rails with this. >> >> The problem I am having (and I have a code example in the github link >> below if you want to see, just clone and run rake spec) is that Sunspot is >> adding an after filter to already loaded subclasses >> of ActionController::Base. >> >> loaded_controllers = >> [base].concat(base.subclasses.map { |subclass| >> subclass.constantize }) >> >> But that map is returning: >> >> ["ActionView::TestCase::TestController", "ApplicationController", >> "#", >> "Spec::Rails::Example::ViewExampleGroupController", >> "Spec::Rails::Example::HelperExampleGroupController"] >> >> So I am trying to find what # is and where it's >> subclassing ActionController. >> >> If I comment out config.gem "rspec-rails" in the environment.rb the >> problem goes away, but that is not a solution as I have boiled this issue >> down to what I have here from a project that is actually using bundler and >> so these gems are being specified and required. >> >> As I do not know what in RSpec::Rails is actually causing the issue I >> cannot raise this as an issue with Sunspot with an example of possibly what >> they should be excluding in their code, if that is the solution to move to. >> >> So if anyone could help me out in any way?? I'm happy to do more "leg >> work" if you could give me some pointers. >> >> Cheers >> Shane >> >> >> git repo showing issue: >> http://github.com/smingins/rspec-sunspot-conflict >> >> using ruby 1.8.7 >> ruby -v >> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Sun Jul 18 21:42:02 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 18 Jul 2010 20:42:02 -0500 Subject: [rspec-users] Gem conflict with RSpec::Rails and Sunspot In-Reply-To: References: Message-ID: On Jul 18, 2010, at 8:21 PM, Shane Mingins wrote: > On 19 July 2010 12:32, Shane Mingins wrote: > Hi All > > I was wondering if someone could perhaps point me to where in RSpec::Rails is the Rails ActionController being subclassed by an Object instance? My ruby-fu is not high enough to work out what's really going on with RSpec::Rails with this. > > The problem I am having (and I have a code example in the github link below if you want to see, just clone and run rake spec) is that Sunspot is adding an after filter to already loaded subclasses of ActionController::Base. > > loaded_controllers = > [base].concat(base.subclasses.map { |subclass| subclass.constantize }) > > But that map is returning: > > ["ActionView::TestCase::TestController", "ApplicationController", "#", > "Spec::Rails::Example::ViewExampleGroupController", "Spec::Rails::Example::HelperExampleGroupController"] > > So I am trying to find what # is and where it's subclassing ActionController. > > If I comment out config.gem "rspec-rails" in the environment.rb the problem goes away, but that is not a solution as I have boiled this issue down to what I have here from a project that is actually using bundler and so these gems are being specified and required. > > As I do not know what in RSpec::Rails is actually causing the issue I cannot raise this as an issue with Sunspot with an example of possibly what they should be excluding in their code, if that is the solution to move to. > > So if anyone could help me out in any way?? I'm happy to do more "leg work" if you could give me some pointers. > > Cheers > Shane > > > git repo showing issue: > http://github.com/smingins/rspec-sunspot-conflict > Seems to be related to the line 'tests Class.new(ActionController::Base)' > > module Spec > module Rails > module Example > > class RoutingExampleGroup < ActionController::TestCase > tests Class.new(ActionController::Base) > > Spec::Example::ExampleGroupFactory.register(:routing, self) > end > > end > end > end Yeah - that looks like it. Given that Class.new(BaseClass) is a common Ruby metaprogramming idiom, this strikes me as a sunspot issue. WDYT? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Sun Jul 18 21:45:24 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 18 Jul 2010 20:45:24 -0500 Subject: [rspec-users] Gem conflict with RSpec::Rails and Sunspot In-Reply-To: References: Message-ID: <59BB0092-AA83-42ED-82BB-569C3053DAB0@gmail.com> On Jul 18, 2010, at 8:29 PM, Shane Mingins wrote: > And so ... > > # Sets the controller class name. Useful if the name can't be inferred from test class. > # Expects +controller_class+ as a constant. Example: tests WidgetController. > def tests(controller_class) > self.controller_class = controller_class > end > > But RoutingExampleGroup is: tests Class.new(ActionController::Base) > > Seems it's being called incorrectly from RoutingExampleGroup, is that right? Class.new(ActionController::Base) is standard Ruby for an anonymous subclass. Nothing incorrect about it, but there's no significant value in having it be anonymous, so I'd be OK changing it to a named subclass (i.e. RoutingExampleGroupController < ActionController::Base). Wanna make a patch? > > > On 19 July 2010 13:21, Shane Mingins wrote: > Seems to be related to the line 'tests Class.new(ActionController::Base)' > > module Spec > module Rails > module Example > > class RoutingExampleGroup < ActionController::TestCase > tests Class.new(ActionController::Base) > > Spec::Example::ExampleGroupFactory.register(:routing, self) > end > > end > end > end > > On 19 July 2010 12:32, Shane Mingins wrote: > Hi All > > I was wondering if someone could perhaps point me to where in RSpec::Rails is the Rails ActionController being subclassed by an Object instance? My ruby-fu is not high enough to work out what's really going on with RSpec::Rails with this. > > The problem I am having (and I have a code example in the github link below if you want to see, just clone and run rake spec) is that Sunspot is adding an after filter to already loaded subclasses of ActionController::Base. > > loaded_controllers = > [base].concat(base.subclasses.map { |subclass| subclass.constantize }) > > But that map is returning: > > ["ActionView::TestCase::TestController", "ApplicationController", "#", > "Spec::Rails::Example::ViewExampleGroupController", "Spec::Rails::Example::HelperExampleGroupController"] > > So I am trying to find what # is and where it's subclassing ActionController. > > If I comment out config.gem "rspec-rails" in the environment.rb the problem goes away, but that is not a solution as I have boiled this issue down to what I have here from a project that is actually using bundler and so these gems are being specified and required. > > As I do not know what in RSpec::Rails is actually causing the issue I cannot raise this as an issue with Sunspot with an example of possibly what they should be excluding in their code, if that is the solution to move to. > > So if anyone could help me out in any way?? I'm happy to do more "leg work" if you could give me some pointers. > > Cheers > Shane > > > git repo showing issue: > http://github.com/smingins/rspec-sunspot-conflict > > using ruby 1.8.7 > ruby -v > ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] > > > _______________________________________________ > 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 elc at mingins.com Sun Jul 18 22:03:20 2010 From: elc at mingins.com (Shane Mingins) Date: Mon, 19 Jul 2010 14:03:20 +1200 Subject: [rspec-users] Gem conflict with RSpec::Rails and Sunspot In-Reply-To: <59BB0092-AA83-42ED-82BB-569C3053DAB0@gmail.com> References: <59BB0092-AA83-42ED-82BB-569C3053DAB0@gmail.com> Message-ID: Does Class.new(ActionController::Base) pass it to tests as a constant though? Reading comment # Expects +controller_class+ as a constant. Example: tests WidgetController. This is just me wondering if I am missing something with that Class.new(ActionController::Base) idiom. Patch would just be a revert of http://github.com/dchelimsky/rspec-rails/commit/b488f3c9bd70011f1288f23b55490810b1fc693dthough right? I can do that and put it on lighthouse if you want ... and it goes up here https://rspec.lighthouseapp.com/projects/5645-rspec ?? And thanks for replying on Sunday :-) Cheers Shane On 19 July 2010 13:45, David Chelimsky wrote: > > On Jul 18, 2010, at 8:29 PM, Shane Mingins wrote: > > And so ... > > # Sets the controller class name. Useful if the name can't be > inferred from test class. > # Expects +controller_class+ as a constant. Example: tests > WidgetController. > def tests(controller_class) > self.controller_class = controller_class > end > > But RoutingExampleGroup is: tests Class.new(ActionController::Base) > > Seems it's being called incorrectly from RoutingExampleGroup, is that > right? > > > Class.new(ActionController::Base) is standard Ruby for an anonymous > subclass. Nothing incorrect about it, but there's no significant value in > having it be anonymous, so I'd be OK changing it to a named subclass (i.e. > RoutingExampleGroupController < ActionController::Base). Wanna make a patch? > > > > On 19 July 2010 13:21, Shane Mingins wrote: > >> Seems to be related to the line 'tests Class.new(ActionController::Base)' >> >> module Spec >> module Rails >> module Example >> >> class RoutingExampleGroup < ActionController::TestCase >> tests Class.new(ActionController::Base) >> >> Spec::Example::ExampleGroupFactory.register(:routing, self) >> end >> >> end >> end >> end >> >> On 19 July 2010 12:32, Shane Mingins wrote: >> >>> Hi All >>> >>> I was wondering if someone could perhaps point me to where in >>> RSpec::Rails is the Rails ActionController being subclassed by an Object >>> instance? My ruby-fu is not high enough to work out what's really going on >>> with RSpec::Rails with this. >>> >>> The problem I am having (and I have a code example in the github link >>> below if you want to see, just clone and run rake spec) is that Sunspot is >>> adding an after filter to already loaded subclasses >>> of ActionController::Base. >>> >>> loaded_controllers = >>> [base].concat(base.subclasses.map { |subclass| >>> subclass.constantize }) >>> >>> But that map is returning: >>> >>> ["ActionView::TestCase::TestController", "ApplicationController", >>> "#", >>> "Spec::Rails::Example::ViewExampleGroupController", >>> "Spec::Rails::Example::HelperExampleGroupController"] >>> >>> So I am trying to find what # is and where it's >>> subclassing ActionController. >>> >>> If I comment out config.gem "rspec-rails" in the environment.rb the >>> problem goes away, but that is not a solution as I have boiled this issue >>> down to what I have here from a project that is actually using bundler and >>> so these gems are being specified and required. >>> >>> As I do not know what in RSpec::Rails is actually causing the issue I >>> cannot raise this as an issue with Sunspot with an example of possibly what >>> they should be excluding in their code, if that is the solution to move to. >>> >>> So if anyone could help me out in any way?? I'm happy to do more "leg >>> work" if you could give me some pointers. >>> >>> Cheers >>> Shane >>> >>> >>> git repo showing issue: >>> http://github.com/smingins/rspec-sunspot-conflict >>> >>> using ruby 1.8.7 >>> ruby -v >>> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] >>> >> >> > _______________________________________________ > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Sun Jul 18 22:12:53 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 18 Jul 2010 21:12:53 -0500 Subject: [rspec-users] Gem conflict with RSpec::Rails and Sunspot In-Reply-To: References: <59BB0092-AA83-42ED-82BB-569C3053DAB0@gmail.com> Message-ID: <3659AEBE-4601-48C2-880E-E571223BB486@gmail.com> On Jul 18, 2010, at 9:03 PM, Shane Mingins wrote: > Does Class.new(ActionController::Base) pass it to tests as a constant though? Reading comment # Expects +controller_class+ as a constant. Example: tests WidgetController. This is just me wondering if I am missing something with that Class.new(ActionController::Base) idiom. > > Patch would just be a revert of http://github.com/dchelimsky/rspec-rails/commit/b488f3c9bd70011f1288f23b55490810b1fc693d though right? > > I can do that and put it on lighthouse if you want ... and it goes up here https://rspec.lighthouseapp.com/projects/5645-rspec ?? Yep - didn't realize it was just a revert (nice research!) but feel free to patch and post it. FYI - I have no plans to do a 1.3.3 release any time soon - too much going on with Rails 3 and RSpec 2 right now. David > And thanks for replying on Sunday :-) > > Cheers > Shane > > On 19 July 2010 13:45, David Chelimsky wrote: > > On Jul 18, 2010, at 8:29 PM, Shane Mingins wrote: > >> And so ... >> >> # Sets the controller class name. Useful if the name can't be inferred from test class. >> # Expects +controller_class+ as a constant. Example: tests WidgetController. >> def tests(controller_class) >> self.controller_class = controller_class >> end >> >> But RoutingExampleGroup is: tests Class.new(ActionController::Base) >> >> Seems it's being called incorrectly from RoutingExampleGroup, is that right? > > Class.new(ActionController::Base) is standard Ruby for an anonymous subclass. Nothing incorrect about it, but there's no significant value in having it be anonymous, so I'd be OK changing it to a named subclass (i.e. RoutingExampleGroupController < ActionController::Base). Wanna make a patch? > >> >> >> On 19 July 2010 13:21, Shane Mingins wrote: >> Seems to be related to the line 'tests Class.new(ActionController::Base)' >> >> module Spec >> module Rails >> module Example >> >> class RoutingExampleGroup < ActionController::TestCase >> tests Class.new(ActionController::Base) >> >> Spec::Example::ExampleGroupFactory.register(:routing, self) >> end >> >> end >> end >> end >> >> On 19 July 2010 12:32, Shane Mingins wrote: >> Hi All >> >> I was wondering if someone could perhaps point me to where in RSpec::Rails is the Rails ActionController being subclassed by an Object instance? My ruby-fu is not high enough to work out what's really going on with RSpec::Rails with this. >> >> The problem I am having (and I have a code example in the github link below if you want to see, just clone and run rake spec) is that Sunspot is adding an after filter to already loaded subclasses of ActionController::Base. >> >> loaded_controllers = >> [base].concat(base.subclasses.map { |subclass| subclass.constantize }) >> >> But that map is returning: >> >> ["ActionView::TestCase::TestController", "ApplicationController", "#", >> "Spec::Rails::Example::ViewExampleGroupController", "Spec::Rails::Example::HelperExampleGroupController"] >> >> So I am trying to find what # is and where it's subclassing ActionController. >> >> If I comment out config.gem "rspec-rails" in the environment.rb the problem goes away, but that is not a solution as I have boiled this issue down to what I have here from a project that is actually using bundler and so these gems are being specified and required. >> >> As I do not know what in RSpec::Rails is actually causing the issue I cannot raise this as an issue with Sunspot with an example of possibly what they should be excluding in their code, if that is the solution to move to. >> >> So if anyone could help me out in any way?? I'm happy to do more "leg work" if you could give me some pointers. >> >> Cheers >> Shane >> >> >> git repo showing issue: >> http://github.com/smingins/rspec-sunspot-conflict >> >> using ruby 1.8.7 >> ruby -v >> ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] >> >> >> _______________________________________________ >> 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 > > _______________________________________________ > 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 matt at mattwynne.net Mon Jul 19 04:58:50 2010 From: matt at mattwynne.net (Matt Wynne) Date: Mon, 19 Jul 2010 09:58:50 +0100 Subject: [rspec-users] Data-wise context combination for controller speccing In-Reply-To: References: Message-ID: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> On 18 Jul 2010, at 00:10, David Chelimsky wrote: > On Jul 17, 2010, at 1:18 PM, Costa Shapiro wrote: > >> Hello, >> >> I've been thinking of how to express my idea in code, but since I've never been involved in RSpec development, I'd better have some feedback here first. >> The feature suggestion below applies to any controller-like code under spec, i.e. a stateless module producing output or just altering its data store (it doesn't necessarily have to be a C of the MVC, but I suppose merb/rails developers will particularly appreciate it). >> >> Here is a skimmed sample to illustrate the pain: >> >> describe BookController do >> >> context "registering a book" do >> >> specify "from a new author on a new subject" do >> auth = mock(:name => 'John Doe') >> Author.should_receive(:find_ >> by_name).and_return(nil) >> Author.should_receive(:new).and_return(auth) >> auth.should_receive(:save).and_return(true) >> >> subj = mock(:short => 'Mockery') >> Subject.should_receive(:find_by_short).and_return(nil) >> Subject.should_receive(:new).and_return(subj) >> subj.should_receive(:save).and_return(true) >> >> title = 'Specs on Steroids' >> >> book = mock >> Book.should_receive(:new).and_return(book) >> book.should_receive(:save).and_return(true) >> >> post :register :author => auth.name, :title => title, :subject => subj.short >> response.should be_success >> end >> >> specify "from a known author on a new subject" do >> auth = mock(:name => 'Joe Dohn') >> Author.should_receive(:find_by_name).and_return(auth) >> >> subj = mock(:short => 'Mockery') >> Subject.should_receive(:find_by_short).and_return(nil) >> Subject.should_receive(:new).and_return(subj) >> subj.should_receive(:save).and_return(true) >> >> title = 'Specs on Steroids II' >> >> book = mock >> Book.should_receive(:new).and_return(book) >> book.should_receive(:save).and_return(true) >> >> post :register :author => auth.name, :title => title, :subject => subj.short >> response.should be_success >> end >> >> specify "from a known author on a known subject" do >> auth = mock(:name => 'Joe Dohn') >> Author.should_receive(:find_by_name).and_return(auth) >> >> subj = mock(:short => 'Forgery') >> Subject.should_receive(:find_by_short).and_return(subj) >> >> #... >> end >> >> specify "from a new author on a known subject" do >> #... >> end >> end >> end >> >> >> And this is what I have in mind for doing exactly the same job: >> >> describe BookController do >> >> context "registering a book" do >> >> before :any, "from a new author", :author do >> @auth = mock(:name => 'John Doe') >> Author.should_receive(:find_by_name).and_return(nil) >> Author.should_receive(:new).and_return(@auth) >> @auth.should_receive(:save).and_return(true) >> end >> >> before :any, "from a known author", :author do >> @auth = mock(:name => 'Joe Dohn') >> Author.should_receive(:find_by_name).and_return(@auth) >> end >> >> before :any, "on a new subject", :subject do >> @subj = mock(:short => 'Mockery') >> Subject.should_receive(:find_by_short).and_return(nil) >> Subject.should_receive(:new).and_return(@subj) >> @subj.should_receive(:save).and_return(true) >> end >> >> before :any, "on a known subject", :subject do >> @subj = mock(:name => 'Joe Dohn') >> Subject.should_receive(:find_by_name).and_return(@subj) >> end >> >> it "should succeed", :with => [:author, :subject] do >> title = 'Specs on Steroids X' >> >> post :register :author => @auth.name, :title => title, :subject => @subj.short >> response.should be_success >> end >> end >> end >> >> A run of such specs will effectively multiply the tests ? automatically ? choosing before and after blocks as specified. >> I'm sorry, I haven't thought the DSL through, but I hope the main idea can be seen: contexts do not have to be hierarchical. >> In my opinion, adding some sort of context selection+combination capabilities (AOP-style) will contribute greatly to the expressiveness of the spec language. > > I think the idea of mixing/matching sub-contexts is very interesting, but it definitely needs from fleshing out. It would have to be easy to read/understand in the spec file as well as the output. > > Also, this only works if every combination should behave the same way. I think we'd need a means of saying "given these combinations of data, expect these outcomes". > > Anybody else have thoughts on this? It's a nice idea. I'm not sure whether I'd use it though. I think this idea comes from the desire to write specs that are *complete*, which I can perfectly understand but I don't think I subscribe to anymore. I prefer to really craft the examples so there's 'just enough' tests but no more than that. I'd be worried this might offer a temptation to think less about why you're writing each example, and I'd be worried how that would help me to do TDD. It should be possible to do something like this using macros now, right? Can I suggest that the OP has a go at refactoring his code using macros and we can see how it looks? > > Cheers, > David > > >> Thank you for your attention, >> Costa. > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users cheers, Matt http://blog.mattwynne.net +44(0)7974 430184 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Mon Jul 19 06:55:57 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 19 Jul 2010 05:55:57 -0500 Subject: [rspec-users] Data-wise context combination for controller speccing In-Reply-To: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> References: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> Message-ID: <7665DACE-09FB-4F4C-BED6-82A750431D94@gmail.com> On Jul 19, 2010, at 3:58 AM, Matt Wynne wrote: > > On 18 Jul 2010, at 00:10, David Chelimsky wrote: > >> On Jul 17, 2010, at 1:18 PM, Costa Shapiro wrote: >> >>> Hello, >>> >>> I've been thinking of how to express my idea in code, but since I've never been involved in RSpec development, I'd better have some feedback here first. >>> The feature suggestion below applies to any controller-like code under spec, i.e. a stateless module producing output or just altering its data store (it doesn't necessarily have to be a C of the MVC, but I suppose merb/rails developers will particularly appreciate it). >>> >>> Here is a skimmed sample to illustrate the pain: >>> >>> describe BookController do >>> >>> context "registering a book" do >>> >>> specify "from a new author on a new subject" do >>> auth = mock(:name => 'John Doe') >>> Author.should_receive(:find_ >>> by_name).and_return(nil) >>> Author.should_receive(:new).and_return(auth) >>> auth.should_receive(:save).and_return(true) >>> >>> subj = mock(:short => 'Mockery') >>> Subject.should_receive(:find_by_short).and_return(nil) >>> Subject.should_receive(:new).and_return(subj) >>> subj.should_receive(:save).and_return(true) >>> >>> title = 'Specs on Steroids' >>> >>> book = mock >>> Book.should_receive(:new).and_return(book) >>> book.should_receive(:save).and_return(true) >>> >>> post :register :author => auth.name, :title => title, :subject => subj.short >>> response.should be_success >>> end >>> >>> specify "from a known author on a new subject" do >>> auth = mock(:name => 'Joe Dohn') >>> Author.should_receive(:find_by_name).and_return(auth) >>> >>> subj = mock(:short => 'Mockery') >>> Subject.should_receive(:find_by_short).and_return(nil) >>> Subject.should_receive(:new).and_return(subj) >>> subj.should_receive(:save).and_return(true) >>> >>> title = 'Specs on Steroids II' >>> >>> book = mock >>> Book.should_receive(:new).and_return(book) >>> book.should_receive(:save).and_return(true) >>> >>> post :register :author => auth.name, :title => title, :subject => subj.short >>> response.should be_success >>> end >>> >>> specify "from a known author on a known subject" do >>> auth = mock(:name => 'Joe Dohn') >>> Author.should_receive(:find_by_name).and_return(auth) >>> >>> subj = mock(:short => 'Forgery') >>> Subject.should_receive(:find_by_short).and_return(subj) >>> >>> #... >>> end >>> >>> specify "from a new author on a known subject" do >>> #... >>> end >>> end >>> end >>> >>> >>> And this is what I have in mind for doing exactly the same job: >>> >>> describe BookController do >>> >>> context "registering a book" do >>> >>> before :any, "from a new author", :author do >>> @auth = mock(:name => 'John Doe') >>> Author.should_receive(:find_by_name).and_return(nil) >>> Author.should_receive(:new).and_return(@auth) >>> @auth.should_receive(:save).and_return(true) >>> end >>> >>> before :any, "from a known author", :author do >>> @auth = mock(:name => 'Joe Dohn') >>> Author.should_receive(:find_by_name).and_return(@auth) >>> end >>> >>> before :any, "on a new subject", :subject do >>> @subj = mock(:short => 'Mockery') >>> Subject.should_receive(:find_by_short).and_return(nil) >>> Subject.should_receive(:new).and_return(@subj) >>> @subj.should_receive(:save).and_return(true) >>> end >>> >>> before :any, "on a known subject", :subject do >>> @subj = mock(:name => 'Joe Dohn') >>> Subject.should_receive(:find_by_name).and_return(@subj) >>> end >>> >>> it "should succeed", :with => [:author, :subject] do >>> title = 'Specs on Steroids X' >>> >>> post :register :author => @auth.name, :title => title, :subject => @subj.short >>> response.should be_success >>> end >>> end >>> end >>> >>> A run of such specs will effectively multiply the tests ? automatically ? choosing before and after blocks as specified. >>> I'm sorry, I haven't thought the DSL through, but I hope the main idea can be seen: contexts do not have to be hierarchical. >>> In my opinion, adding some sort of context selection+combination capabilities (AOP-style) will contribute greatly to the expressiveness of the spec language. >> >> I think the idea of mixing/matching sub-contexts is very interesting, but it definitely needs from fleshing out. It would have to be easy to read/understand in the spec file as well as the output. >> >> Also, this only works if every combination should behave the same way. I think we'd need a means of saying "given these combinations of data, expect these outcomes". >> >> Anybody else have thoughts on this? > > It's a nice idea. > > I'm not sure whether I'd use it though. I think this idea comes from the desire to write specs that are *complete*, which I can perfectly understand but I don't think I subscribe to anymore. I prefer to really craft the examples so there's 'just enough' tests but no more than that. I'd be worried this might offer a temptation to think less about why you're writing each example, and I'd be worried how that would help me to do TDD. Agreed this would be a potential pitfall of this approach. I'm also not convinced this is the right tool for this sort of thing. Seems like something best expressed in a table: data do author do new { ... } known { ... } end subject do new { ... } known { ... } end outcome do success { ... } end end scenarios <<-SCENARIOS | author | subject | outcome | | new | new | success | | known | new | success | | new | known | success | | known | known | success | SCENARIOS Something like this might work, but maybe it's better suited for Cucumber, or FIT. > It should be possible to do something like this using macros now, right? Can I suggest that the OP has a go at refactoring his code using macros and we can see how it looks? > >> >> Cheers, >> David >> >> >>> Thank you for your attention, >>> Costa. >> >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users > > cheers, > Matt > > http://blog.mattwynne.net > +44(0)7974 430184 > > _______________________________________________ > 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 win at wincent.com Mon Jul 19 06:38:41 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 19 Jul 2010 12:38:41 +0200 Subject: [rspec-users] Data-wise context combination for controller speccing In-Reply-To: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> References: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> Message-ID: <327DFD8F-7A09-49B5-B985-328A77DF0876@wincent.com> El 19/07/2010, a las 10:58, Matt Wynne escribi?: > On 18 Jul 2010, at 00:10, David Chelimsky wrote: > >> On Jul 17, 2010, at 1:18 PM, Costa Shapiro wrote: >> >>> Hello, >>> >>> I've been thinking of how to express my idea in code, but since I've never been involved in RSpec development, I'd better have some feedback here first. >>> The feature suggestion below applies to any controller-like code under spec, i.e. a stateless module producing output or just altering its data store (it doesn't necessarily have to be a C of the MVC, but I suppose merb/rails developers will particularly appreciate it). >>> >>> Here is a skimmed sample to illustrate the pain: >>> >>> describe BookController do >>> >>> context "registering a book" do >>> >>> specify "from a new author on a new subject" do >>> auth = mock(:name => 'John Doe') >>> Author.should_receive(:find_ >>> by_name).and_return(nil) >>> Author.should_receive(:new).and_return(auth) >>> auth.should_receive(:save).and_return(true) >>> >>> subj = mock(:short => 'Mockery') >>> Subject.should_receive(:find_by_short).and_return(nil) >>> Subject.should_receive(:new).and_return(subj) >>> subj.should_receive(:save).and_return(true) >>> >>> title = 'Specs on Steroids' >>> >>> book = mock >>> Book.should_receive(:new).and_return(book) >>> book.should_receive(:save).and_return(true) >>> >>> post :register :author => auth.name, :title => title, :subject => subj.short >>> response.should be_success >>> end >>> >>> specify "from a known author on a new subject" do >>> auth = mock(:name => 'Joe Dohn') >>> Author.should_receive(:find_by_name).and_return(auth) >>> >>> subj = mock(:short => 'Mockery') >>> Subject.should_receive(:find_by_short).and_return(nil) >>> Subject.should_receive(:new).and_return(subj) >>> subj.should_receive(:save).and_return(true) >>> >>> title = 'Specs on Steroids II' >>> >>> book = mock >>> Book.should_receive(:new).and_return(book) >>> book.should_receive(:save).and_return(true) >>> >>> post :register :author => auth.name, :title => title, :subject => subj.short >>> response.should be_success >>> end >>> >>> specify "from a known author on a known subject" do >>> auth = mock(:name => 'Joe Dohn') >>> Author.should_receive(:find_by_name).and_return(auth) >>> >>> subj = mock(:short => 'Forgery') >>> Subject.should_receive(:find_by_short).and_return(subj) >>> >>> #... >>> end >>> >>> specify "from a new author on a known subject" do >>> #... >>> end >>> end >>> end >>> >>> >>> And this is what I have in mind for doing exactly the same job: >>> >>> describe BookController do >>> >>> context "registering a book" do >>> >>> before :any, "from a new author", :author do >>> @auth = mock(:name => 'John Doe') >>> Author.should_receive(:find_by_name).and_return(nil) >>> Author.should_receive(:new).and_return(@auth) >>> @auth.should_receive(:save).and_return(true) >>> end >>> >>> before :any, "from a known author", :author do >>> @auth = mock(:name => 'Joe Dohn') >>> Author.should_receive(:find_by_name).and_return(@auth) >>> end >>> >>> before :any, "on a new subject", :subject do >>> @subj = mock(:short => 'Mockery') >>> Subject.should_receive(:find_by_short).and_return(nil) >>> Subject.should_receive(:new).and_return(@subj) >>> @subj.should_receive(:save).and_return(true) >>> end >>> >>> before :any, "on a known subject", :subject do >>> @subj = mock(:name => 'Joe Dohn') >>> Subject.should_receive(:find_by_name).and_return(@subj) >>> end >>> >>> it "should succeed", :with => [:author, :subject] do >>> title = 'Specs on Steroids X' >>> >>> post :register :author => @auth.name, :title => title, :subject => @subj.short >>> response.should be_success >>> end >>> end >>> end >>> >>> A run of such specs will effectively multiply the tests ? automatically ? choosing before and after blocks as specified. >>> I'm sorry, I haven't thought the DSL through, but I hope the main idea can be seen: contexts do not have to be hierarchical. >>> In my opinion, adding some sort of context selection+combination capabilities (AOP-style) will contribute greatly to the expressiveness of the spec language. >> >> I think the idea of mixing/matching sub-contexts is very interesting, but it definitely needs from fleshing out. It would have to be easy to read/understand in the spec file as well as the output. >> >> Also, this only works if every combination should behave the same way. I think we'd need a means of saying "given these combinations of data, expect these outcomes". >> >> Anybody else have thoughts on this? > > It's a nice idea. > > I'm not sure whether I'd use it though. I think this idea comes from the desire to write specs that are *complete*, which I can perfectly understand but I don't think I subscribe to anymore. I prefer to really craft the examples so there's 'just enough' tests but no more than that. I'd be worried this might offer a temptation to think less about why you're writing each example, and I'd be worried how that would help me to do TDD. > > It should be possible to do something like this using macros now, right? Can I suggest that the OP has a go at refactoring his code using macros and we can see how it looks? I know that the posted code may be a contrived toy example for the purposes of illustration, but when I see a spec like that alarm bells start to ring. So much mocking, so many assertions in each example block etc. And it's not at all clear what the pertinent behavior is that you want to test here, because each example looks exactly like a one-to-one rewrite of the original implementation that uses mocks instead of real objects. And when the alarm bells start to ring, before I think about changing my testing framework to make things easier, I look at the code under test to see if it could be changed to be more testable. So we basically have a controller action that accepts three parameters (author, title, and subject), and it has a conditional code path for two of those: if thing.exists great else create it end And in your spec you're wanting to test for all the different permutations of new author/existing author and new subject/existing subject. First thing you could do to eliminate a lot of mocking is use something like "find_or_create_by_name" and "find_or_create_by_short". Then you only have to mock three calls (one for each parameter) and forget about the permutations entirely. This is an example of pushing logic down into the model in order to make controllers simpler and more testable. If "find_or_create_by_*" doesn't do what you need it to, then create a model method which does. You could go even further and create a "register" method on your Book class which accepted the three parameters of author, title, and subject, and did everything which you are currently doing in your controller in the model layer instead. Then your controller spec becomes ridiculously simple, can be tested with a single mock, and the rest of the logic now resides in a model, which is easily testable. So whether or not the example was a toy example, the need for the any automatic permutation and spec generation in RSpec has disappeared. Let's imagine, however, that the need was still there. Would adding this kind of code to RSpec itself be a good idea? I don't necessarily think so. Matt says you can probably do this right now by using macros. I don't actually know what he means by that, but I do know that there are cases where I sometimes want a bunch of nearly identical specs, and I generate them in code using enumeration or some other means; ie. dumb example: [:foo, :bar, :baz].do |thing| describe "#{thing} dimensions" do it 'has length' do thing.to_s.length.should > 0 end end end So like I said, if your tests are painful, I think the first port of call should be to look at how the code under test could be change. Good code isn't just code that works. It's also code that is readable, maintainable, any among many other things, testable. Adding support to RSpec to make it easier to test bad code doesn't seem the right thing to do. Maybe you have another example that could illustrate how what you propose would be useful, but right now I don't really see the need for this kind of thing. Cheers, Wincent From matt at mattwynne.net Mon Jul 19 08:54:23 2010 From: matt at mattwynne.net (Matt Wynne) Date: Mon, 19 Jul 2010 13:54:23 +0100 Subject: [rspec-users] Data-wise context combination for controller speccing In-Reply-To: <327DFD8F-7A09-49B5-B985-328A77DF0876@wincent.com> References: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> <327DFD8F-7A09-49B5-B985-328A77DF0876@wincent.com> Message-ID: <0AB75080-A3D4-4283-BC25-CFE5532E1BAE@mattwynne.net> On 19 Jul 2010, at 11:38, Wincent Colaiuta wrote: > El 19/07/2010, a las 10:58, Matt Wynne escribi?: > >> On 18 Jul 2010, at 00:10, David Chelimsky wrote: >> >>> On Jul 17, 2010, at 1:18 PM, Costa Shapiro wrote: >>> >>>> Hello, >>>> >>>> I've been thinking of how to express my idea in code, but since I've never been involved in RSpec development, I'd better have some feedback here first. >>>> The feature suggestion below applies to any controller-like code under spec, i.e. a stateless module producing output or just altering its data store (it doesn't necessarily have to be a C of the MVC, but I suppose merb/rails developers will particularly appreciate it). >>>> >>>> Here is a skimmed sample to illustrate the pain: >>>> >>>> describe BookController do >>>> >>>> context "registering a book" do >>>> >>>> specify "from a new author on a new subject" do >>>> auth = mock(:name => 'John Doe') >>>> Author.should_receive(:find_ >>>> by_name).and_return(nil) >>>> Author.should_receive(:new).and_return(auth) >>>> auth.should_receive(:save).and_return(true) >>>> >>>> subj = mock(:short => 'Mockery') >>>> Subject.should_receive(:find_by_short).and_return(nil) >>>> Subject.should_receive(:new).and_return(subj) >>>> subj.should_receive(:save).and_return(true) >>>> >>>> title = 'Specs on Steroids' >>>> >>>> book = mock >>>> Book.should_receive(:new).and_return(book) >>>> book.should_receive(:save).and_return(true) >>>> >>>> post :register :author => auth.name, :title => title, :subject => subj.short >>>> response.should be_success >>>> end >>>> >>>> specify "from a known author on a new subject" do >>>> auth = mock(:name => 'Joe Dohn') >>>> Author.should_receive(:find_by_name).and_return(auth) >>>> >>>> subj = mock(:short => 'Mockery') >>>> Subject.should_receive(:find_by_short).and_return(nil) >>>> Subject.should_receive(:new).and_return(subj) >>>> subj.should_receive(:save).and_return(true) >>>> >>>> title = 'Specs on Steroids II' >>>> >>>> book = mock >>>> Book.should_receive(:new).and_return(book) >>>> book.should_receive(:save).and_return(true) >>>> >>>> post :register :author => auth.name, :title => title, :subject => subj.short >>>> response.should be_success >>>> end >>>> >>>> specify "from a known author on a known subject" do >>>> auth = mock(:name => 'Joe Dohn') >>>> Author.should_receive(:find_by_name).and_return(auth) >>>> >>>> subj = mock(:short => 'Forgery') >>>> Subject.should_receive(:find_by_short).and_return(subj) >>>> >>>> #... >>>> end >>>> >>>> specify "from a new author on a known subject" do >>>> #... >>>> end >>>> end >>>> end >>>> >>>> >>>> And this is what I have in mind for doing exactly the same job: >>>> >>>> describe BookController do >>>> >>>> context "registering a book" do >>>> >>>> before :any, "from a new author", :author do >>>> @auth = mock(:name => 'John Doe') >>>> Author.should_receive(:find_by_name).and_return(nil) >>>> Author.should_receive(:new).and_return(@auth) >>>> @auth.should_receive(:save).and_return(true) >>>> end >>>> >>>> before :any, "from a known author", :author do >>>> @auth = mock(:name => 'Joe Dohn') >>>> Author.should_receive(:find_by_name).and_return(@auth) >>>> end >>>> >>>> before :any, "on a new subject", :subject do >>>> @subj = mock(:short => 'Mockery') >>>> Subject.should_receive(:find_by_short).and_return(nil) >>>> Subject.should_receive(:new).and_return(@subj) >>>> @subj.should_receive(:save).and_return(true) >>>> end >>>> >>>> before :any, "on a known subject", :subject do >>>> @subj = mock(:name => 'Joe Dohn') >>>> Subject.should_receive(:find_by_name).and_return(@subj) >>>> end >>>> >>>> it "should succeed", :with => [:author, :subject] do >>>> title = 'Specs on Steroids X' >>>> >>>> post :register :author => @auth.name, :title => title, :subject => @subj.short >>>> response.should be_success >>>> end >>>> end >>>> end >>>> >>>> A run of such specs will effectively multiply the tests ? automatically ? choosing before and after blocks as specified. >>>> I'm sorry, I haven't thought the DSL through, but I hope the main idea can be seen: contexts do not have to be hierarchical. >>>> In my opinion, adding some sort of context selection+combination capabilities (AOP-style) will contribute greatly to the expressiveness of the spec language. >>> >>> I think the idea of mixing/matching sub-contexts is very interesting, but it definitely needs from fleshing out. It would have to be easy to read/understand in the spec file as well as the output. >>> >>> Also, this only works if every combination should behave the same way. I think we'd need a means of saying "given these combinations of data, expect these outcomes". >>> >>> Anybody else have thoughts on this? >> >> It's a nice idea. >> >> I'm not sure whether I'd use it though. I think this idea comes from the desire to write specs that are *complete*, which I can perfectly understand but I don't think I subscribe to anymore. I prefer to really craft the examples so there's 'just enough' tests but no more than that. I'd be worried this might offer a temptation to think less about why you're writing each example, and I'd be worried how that would help me to do TDD. >> >> It should be possible to do something like this using macros now, right? Can I suggest that the OP has a go at refactoring his code using macros and we can see how it looks? > > I know that the posted code may be a contrived toy example for the purposes of illustration, but when I see a spec like that alarm bells start to ring. So much mocking, so many assertions in each example block etc. And it's not at all clear what the pertinent behavior is that you want to test here, because each example looks exactly like a one-to-one rewrite of the original implementation that uses mocks instead of real objects. > > And when the alarm bells start to ring, before I think about changing my testing framework to make things easier, I look at the code under test to see if it could be changed to be more testable. > > So we basically have a controller action that accepts three parameters (author, title, and subject), and it has a conditional code path for two of those: > > if thing.exists > great > else > create it > end > > And in your spec you're wanting to test for all the different permutations of new author/existing author and new subject/existing subject. > > First thing you could do to eliminate a lot of mocking is use something like "find_or_create_by_name" and "find_or_create_by_short". Then you only have to mock three calls (one for each parameter) and forget about the permutations entirely. > > This is an example of pushing logic down into the model in order to make controllers simpler and more testable. If "find_or_create_by_*" doesn't do what you need it to, then create a model method which does. > > You could go even further and create a "register" method on your Book class which accepted the three parameters of author, title, and subject, and did everything which you are currently doing in your controller in the model layer instead. Then your controller spec becomes ridiculously simple, can be tested with a single mock, and the rest of the logic now resides in a model, which is easily testable. > > So whether or not the example was a toy example, the need for the any automatic permutation and spec generation in RSpec has disappeared. Let's imagine, however, that the need was still there. Would adding this kind of code to RSpec itself be a good idea? > > I don't necessarily think so. Matt says you can probably do this right now by using macros. I don't actually know what he means by that, but I do know that there are cases where I sometimes want a bunch of nearly identical specs, and I generate them in code using enumeration or some other means; ie. dumb example: > > [:foo, :bar, :baz].do |thing| > describe "#{thing} dimensions" do > it 'has length' do > thing.to_s.length.should > 0 > end > end > end That's the kind of thing I meant by macro, yes. Is that a well-understood use of the word? > > So like I said, if your tests are painful, I think the first port of call should be to look at how the code under test could be change. Good code isn't just code that works. It's also code that is readable, maintainable, any among many other things, testable. Adding support to RSpec to make it easier to test bad code doesn't seem the right thing to do. > > Maybe you have another example that could illustrate how what you propose would be useful, but right now I don't really see the need for this kind of thing. > > Cheers, > Wincent > > > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users cheers, Matt http://blog.mattwynne.net +44(0)7974 430184 From rogerpack2005 at gmail.com Mon Jul 19 09:17:19 2010 From: rogerpack2005 at gmail.com (rogerdpack) Date: Mon, 19 Jul 2010 06:17:19 -0700 (PDT) Subject: [rspec-users] rspec2 help output has brackets? Message-ID: Hi all. Saw this: Usage: rspec [options] [files or directories] -b, --backtrace Enable full backtrace -c, --[no-]color, --[no-]colour Enable color in the output -d, --debug Enable debugging -e, --example PATTERN Run examples whose full descriptions match this pattern (PATTERN is compiled into a Ruby regular expression) -f, --format FORMATTER Choose a formatter [p]rogress (default - dots) [d]ocumentation (group and example names) [h]tml [t]extmate custom formatter class name tried this: $ rspec -fp (for the [p] in [p]rogress) got this: Exception `ArgumentError' at c:/dev/ruby/downloads/jruby/lib/ruby/gems/ 1.8/gems/rspec-core-2.0.0.beta.17/lib/rspec/core/configuration.rb:191 - Formatter 'p' unknown - maybe you meant 'documentation' or 'progress'?. c:/dev/ruby/downloads/jruby/lib/ruby/gems/1.8/gems/rspec- core-2.0.0.beta.17/lib/rspec/core/configuration.rb:191:in `formatter=': Formatter 'p' unknown - maybe you meant 'documentation' or 'progress'?. (ArgumentError) is this expected? Thanks. -r From dchelimsky at gmail.com Mon Jul 19 09:52:02 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 19 Jul 2010 08:52:02 -0500 Subject: [rspec-users] rspec2 help output has brackets? In-Reply-To: References: Message-ID: <4116B95B-7E55-4871-99F1-F9ACA1D55B29@gmail.com> On Jul 19, 2010, at 8:17 AM, rogerdpack wrote: > Hi all. > > Saw this: > > Usage: rspec [options] [files or directories] > -b, --backtrace Enable full backtrace > -c, --[no-]color, --[no-]colour Enable color in the output > -d, --debug Enable debugging > -e, --example PATTERN Run examples whose full > descriptions match this pattern > (PATTERN is compiled into a Ruby > regular expression) > -f, --format FORMATTER Choose a formatter > [p]rogress (default - dots) > [d]ocumentation (group and > example names) > [h]tml > [t]extmate > custom formatter class name > > tried this: > $ rspec -fp (for the [p] in [p]rogress) > > got this: > > Exception `ArgumentError' at c:/dev/ruby/downloads/jruby/lib/ruby/gems/ > 1.8/gems/rspec-core-2.0.0.beta.17/lib/rspec/core/configuration.rb:191 > - Formatter 'p' unknown - maybe you meant 'documentation' or > 'progress'?. > c:/dev/ruby/downloads/jruby/lib/ruby/gems/1.8/gems/rspec- > core-2.0.0.beta.17/lib/rspec/core/configuration.rb:191:in > `formatter=': Formatter 'p' unknown - maybe you meant 'documentation' > or 'progress'?. (ArgumentError) > > is this expected? Nope. Bug. rspec-core bugs go here: http://github.com/rspec/rspec-core/issues Thx, David > Thanks. > -r From phillipkoebbe at gmail.com Mon Jul 19 10:20:50 2010 From: phillipkoebbe at gmail.com (Phillip Koebbe) Date: Mon, 19 Jul 2010 09:20:50 -0500 Subject: [rspec-users] Data-wise context combination for controller speccing In-Reply-To: <327DFD8F-7A09-49B5-B985-328A77DF0876@wincent.com> References: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> <327DFD8F-7A09-49B5-B985-328A77DF0876@wincent.com> Message-ID: <4C445F42.2050305@gmail.com> On 2010-07-19 5:38 AM, Wincent Colaiuta wrote: > El 19/07/2010, a las 10:58, Matt Wynne escribi?: > >> On 18 Jul 2010, at 00:10, David Chelimsky wrote: >> >>> On Jul 17, 2010, at 1:18 PM, Costa Shapiro wrote: >>> >>>> Hello, >>>> >>>> I've been thinking of how to express my idea in code, but since I've never been involved in RSpec development, I'd better have some feedback here first. >>>> The feature suggestion below applies to any controller-like code under spec, i.e. a stateless module producing output or just altering its data store (it doesn't necessarily have to be a C of the MVC, but I suppose merb/rails developers will particularly appreciate it). >>>> >>>> Here is a skimmed sample to illustrate the pain: >>>> >>>> describe BookController do >>>> >>>> context "registering a book" do >>>> >>>> specify "from a new author on a new subject" do >>>> auth = mock(:name => 'John Doe') >>>> Author.should_receive(:find_ >>>> by_name).and_return(nil) >>>> Author.should_receive(:new).and_return(auth) >>>> auth.should_receive(:save).and_return(true) >>>> >>>> subj = mock(:short => 'Mockery') >>>> Subject.should_receive(:find_by_short).and_return(nil) >>>> Subject.should_receive(:new).and_return(subj) >>>> subj.should_receive(:save).and_return(true) >>>> >>>> title = 'Specs on Steroids' >>>> >>>> book = mock >>>> Book.should_receive(:new).and_return(book) >>>> book.should_receive(:save).and_return(true) >>>> >>>> post :register :author => auth.name, :title => title, :subject => subj.short >>>> response.should be_success >>>> end >>>> >>>> specify "from a known author on a new subject" do >>>> auth = mock(:name => 'Joe Dohn') >>>> Author.should_receive(:find_by_name).and_return(auth) >>>> >>>> subj = mock(:short => 'Mockery') >>>> Subject.should_receive(:find_by_short).and_return(nil) >>>> Subject.should_receive(:new).and_return(subj) >>>> subj.should_receive(:save).and_return(true) >>>> >>>> title = 'Specs on Steroids II' >>>> >>>> book = mock >>>> Book.should_receive(:new).and_return(book) >>>> book.should_receive(:save).and_return(true) >>>> >>>> post :register :author => auth.name, :title => title, :subject => subj.short >>>> response.should be_success >>>> end >>>> >>>> specify "from a known author on a known subject" do >>>> auth = mock(:name => 'Joe Dohn') >>>> Author.should_receive(:find_by_name).and_return(auth) >>>> >>>> subj = mock(:short => 'Forgery') >>>> Subject.should_receive(:find_by_short).and_return(subj) >>>> >>>> #... >>>> end >>>> >>>> specify "from a new author on a known subject" do >>>> #... >>>> end >>>> end >>>> end >>>> >>>> >>>> And this is what I have in mind for doing exactly the same job: >>>> >>>> describe BookController do >>>> >>>> context "registering a book" do >>>> >>>> before :any, "from a new author", :author do >>>> @auth = mock(:name => 'John Doe') >>>> Author.should_receive(:find_by_name).and_return(nil) >>>> Author.should_receive(:new).and_return(@auth) >>>> @auth.should_receive(:save).and_return(true) >>>> end >>>> >>>> before :any, "from a known author", :author do >>>> @auth = mock(:name => 'Joe Dohn') >>>> Author.should_receive(:find_by_name).and_return(@auth) >>>> end >>>> >>>> before :any, "on a new subject", :subject do >>>> @subj = mock(:short => 'Mockery') >>>> Subject.should_receive(:find_by_short).and_return(nil) >>>> Subject.should_receive(:new).and_return(@subj) >>>> @subj.should_receive(:save).and_return(true) >>>> end >>>> >>>> before :any, "on a known subject", :subject do >>>> @subj = mock(:name => 'Joe Dohn') >>>> Subject.should_receive(:find_by_name).and_return(@subj) >>>> end >>>> >>>> it "should succeed", :with => [:author, :subject] do >>>> title = 'Specs on Steroids X' >>>> >>>> post :register :author => @auth.name, :title => title, :subject => @subj.short >>>> response.should be_success >>>> end >>>> end >>>> end >>>> >>>> A run of such specs will effectively multiply the tests ? automatically ? choosing before and after blocks as specified. >>>> I'm sorry, I haven't thought the DSL through, but I hope the main idea can be seen: contexts do not have to be hierarchical. >>>> In my opinion, adding some sort of context selection+combination capabilities (AOP-style) will contribute greatly to the expressiveness of the spec language. >>> I think the idea of mixing/matching sub-contexts is very interesting, but it definitely needs from fleshing out. It would have to be easy to read/understand in the spec file as well as the output. >>> >>> Also, this only works if every combination should behave the same way. I think we'd need a means of saying "given these combinations of data, expect these outcomes". >>> >>> Anybody else have thoughts on this? >> It's a nice idea. >> >> I'm not sure whether I'd use it though. I think this idea comes from the desire to write specs that are *complete*, which I can perfectly understand but I don't think I subscribe to anymore. I prefer to really craft the examples so there's 'just enough' tests but no more than that. I'd be worried this might offer a temptation to think less about why you're writing each example, and I'd be worried how that would help me to do TDD. >> >> It should be possible to do something like this using macros now, right? Can I suggest that the OP has a go at refactoring his code using macros and we can see how it looks? > I know that the posted code may be a contrived toy example for the purposes of illustration, but when I see a spec like that alarm bells start to ring. So much mocking, so many assertions in each example block etc. And it's not at all clear what the pertinent behavior is that you want to test here, because each example looks exactly like a one-to-one rewrite of the original implementation that uses mocks instead of real objects. > > And when the alarm bells start to ring, before I think about changing my testing framework to make things easier, I look at the code under test to see if it could be changed to be more testable. > > So we basically have a controller action that accepts three parameters (author, title, and subject), and it has a conditional code path for two of those: > > if thing.exists > great > else > create it > end > > And in your spec you're wanting to test for all the different permutations of new author/existing author and new subject/existing subject. > > First thing you could do to eliminate a lot of mocking is use something like "find_or_create_by_name" and "find_or_create_by_short". Then you only have to mock three calls (one for each parameter) and forget about the permutations entirely. > > This is an example of pushing logic down into the model in order to make controllers simpler and more testable. If "find_or_create_by_*" doesn't do what you need it to, then create a model method which does. > > You could go even further and create a "register" method on your Book class which accepted the three parameters of author, title, and subject, and did everything which you are currently doing in your controller in the model layer instead. Then your controller spec becomes ridiculously simple, can be tested with a single mock, and the rest of the logic now resides in a model, which is easily testable. > > So whether or not the example was a toy example, the need for the any automatic permutation and spec generation in RSpec has disappeared. Let's imagine, however, that the need was still there. Would adding this kind of code to RSpec itself be a good idea? > > I don't necessarily think so. Matt says you can probably do this right now by using macros. I don't actually know what he means by that, but I do know that there are cases where I sometimes want a bunch of nearly identical specs, and I generate them in code using enumeration or some other means; ie. dumb example: > > [:foo, :bar, :baz].do |thing| > describe "#{thing} dimensions" do > it 'has length' do > thing.to_s.length.should> 0 > end > end > end > Glad to see I'm not the only one that does this. :) Peace, Phillip From win at wincent.com Mon Jul 19 10:20:26 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 19 Jul 2010 16:20:26 +0200 Subject: [rspec-users] rspec2 help output has brackets? In-Reply-To: <4116B95B-7E55-4871-99F1-F9ACA1D55B29@gmail.com> References: <4116B95B-7E55-4871-99F1-F9ACA1D55B29@gmail.com> Message-ID: <4A4F5511-0E82-4A52-94C3-859F8BC6CCD3@wincent.com> El 19/07/2010, a las 15:52, David Chelimsky escribi?: > On Jul 19, 2010, at 8:17 AM, rogerdpack wrote: > >> Hi all. >> >> Saw this: >> >> Usage: rspec [options] [files or directories] >> -b, --backtrace Enable full backtrace >> -c, --[no-]color, --[no-]colour Enable color in the output >> -d, --debug Enable debugging >> -e, --example PATTERN Run examples whose full >> descriptions match this pattern >> (PATTERN is compiled into a Ruby >> regular expression) >> -f, --format FORMATTER Choose a formatter >> [p]rogress (default - dots) >> [d]ocumentation (group and >> example names) >> [h]tml >> [t]extmate >> custom formatter class name >> >> tried this: >> $ rspec -fp (for the [p] in [p]rogress) >> >> got this: >> >> Exception `ArgumentError' at c:/dev/ruby/downloads/jruby/lib/ruby/gems/ >> 1.8/gems/rspec-core-2.0.0.beta.17/lib/rspec/core/configuration.rb:191 >> - Formatter 'p' unknown - maybe you meant 'documentation' or >> 'progress'?. >> c:/dev/ruby/downloads/jruby/lib/ruby/gems/1.8/gems/rspec- >> core-2.0.0.beta.17/lib/rspec/core/configuration.rb:191:in >> `formatter=': Formatter 'p' unknown - maybe you meant 'documentation' >> or 'progress'?. (ArgumentError) >> >> is this expected? > > Nope. Bug. rspec-core bugs go here: http://github.com/rspec/rspec-core/issues In the meantime, "rspec -f p" (with a space) works fine. Wincent From win at wincent.com Mon Jul 19 11:12:18 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 19 Jul 2010 17:12:18 +0200 Subject: [rspec-users] Data-wise context combination for controller speccing In-Reply-To: <4C445F42.2050305@gmail.com> References: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> <327DFD8F-7A09-49B5-B985-328A77DF0876@wincent.com> <4C445F42.2050305@gmail.com> Message-ID: <4A09A2AF-061C-4C30-A50B-0D47762C25B2@wincent.com> El 19/07/2010, a las 16:20, Phillip Koebbe escribi?: > On 2010-07-19 5:38 AM, Wincent Colaiuta wrote: >> I don't necessarily think so. Matt says you can probably do this right now by using macros. I don't actually know what he means by that, but I do know that there are cases where I sometimes want a bunch of nearly identical specs, and I generate them in code using enumeration or some other means; ie. dumb example: >> >> [:foo, :bar, :baz].do |thing| >> describe "#{thing} dimensions" do >> it 'has length' do >> thing.to_s.length.should> 0 >> end >> end >> end >> > > Glad to see I'm not the only one that does this. :) Yeah, I think it's a legitimate technique, as long as you don't get too carried away with it. I use it, for example, for some code quality specs: Wincent::SOURCE_FILES.each do |file| describe file do it 'contains no trailing whitespace' do file.should_not have_trailing_whitespace end it 'contains no tabs' do file.should_not contain_tabs end it 'has a newline at the end' do file.should have_newline_at_end_of_file end end end Cheers, Wincent From lists at ruby-forum.com Mon Jul 19 14:05:58 2010 From: lists at ruby-forum.com (Walther Diechmann) Date: Mon, 19 Jul 2010 20:05:58 +0200 Subject: [rspec-users] How do I setup Rspec, Cucumber to test a Gem? Message-ID: Hi, my question unwields me as a complete noob - which is okay - but I apologize for this totally basic question <:) I've bought the PragProg Rspec Book and googled, been reading blogs and what-have-I-not, but nowhere have I been able to find information detailing how I setup a BDD environment for testing the construction of a Gem. I have a ../gem_folder which I hope eventually will be a Gem to use with Rails 3 and I really would like to upload it to GitHub with a good test coverage. >From the Rspec Book I've learned that within Rails Apps, I use Cucumber and WebRat (among others) - but the book does not (or at least I?ve not been able to discover it) show how to setup the environment, without the Rails App. I guess my question could boil down to: how do I create the environment (folders, files) to test a Gem meant to work with Rails? So far I have: ../gem_folder ../gem_folder/features ../gem_folder/lib ../gem_folder/pkg ../gem_folder/spec and a few files like Rakefile, Manifest, CHANGELOG, LICENSE - and I'm able to push to Gemcutter and GitHub but where in this picture does the Rails App fit in? How do I make sure that the Gem will work went installed/utilized on Rails App's best regards, Walther -- Posted via http://www.ruby-forum.com/. From matt at mattwynne.net Mon Jul 19 15:12:39 2010 From: matt at mattwynne.net (Matt Wynne) Date: Mon, 19 Jul 2010 20:12:39 +0100 Subject: [rspec-users] How do I setup Rspec, Cucumber to test a Gem? In-Reply-To: References: Message-ID: <1E1DB7ED-70BE-4C7E-9A91-543528D73E59@mattwynne.net> On 19 Jul 2010, at 19:05, Walther Diechmann wrote: > Hi, > > my question unwields me as a complete noob - which is okay - but I > apologize for this totally basic question <:) > > I've bought the PragProg Rspec Book and googled, been reading blogs and > what-have-I-not, but nowhere have I been able to find information > detailing how I setup a BDD environment for testing the construction of > a Gem. > > I have a ../gem_folder which I hope eventually will be a Gem to use with > Rails 3 and I really would like to upload it to GitHub with a good test > coverage. > > From the Rspec Book I've learned that within Rails Apps, I use Cucumber > and WebRat (among others) - but the book does not (or at least I?ve not > been able to discover it) show how to setup the environment, without the > Rails App. > > I guess my question could boil down to: how do I create the environment > (folders, files) to test a Gem meant to work with Rails? > > So far I have: > > ../gem_folder > ../gem_folder/features > ../gem_folder/lib > ../gem_folder/pkg > ../gem_folder/spec > > and a few files like Rakefile, Manifest, CHANGELOG, LICENSE - and I'm > able to push to Gemcutter and GitHub > > but where in this picture does the Rails App fit in? How do I make sure > that the Gem will work went installed/utilized on Rails App's > > best regards, > Walther > -- > Posted via http://www.ruby-forum.com/. The rspec-rails gem is probably a good example for you to read for ideas. http://github.com/rspec/rspec-rails/tree/master > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users cheers, Matt http://blog.mattwynne.net +44(0)7974 430184 From dchelimsky at gmail.com Mon Jul 19 20:47:12 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 19 Jul 2010 19:47:12 -0500 Subject: [rspec-users] deprecate mock_model? Message-ID: <97F2F654-9B02-4140-B8E3-523E6CD050F4@gmail.com> Hey all, I'm thinking of deprecating mock_model in rspec-rails-2. stub_model is more stable, reliable (not dependent on Rails internals like mock_model is), much less intrusive, and I find that I use it all the time in spite of the need to create a real model to back it up. Anybody attached to mock_model? If so, please make your case. Cheers, David From dchelimsky at gmail.com Mon Jul 19 23:33:47 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 19 Jul 2010 22:33:47 -0500 Subject: [rspec-users] deprecate mock_model? In-Reply-To: <97F2F654-9B02-4140-B8E3-523E6CD050F4@gmail.com> References: <97F2F654-9B02-4140-B8E3-523E6CD050F4@gmail.com> Message-ID: On Jul 19, 2010, at 7:47 PM, David Chelimsky wrote: > Hey all, > > I'm thinking of deprecating mock_model in rspec-rails-2. stub_model is more stable, reliable (not dependent on Rails internals like mock_model is), much less intrusive, and I find that I use it all the time in spite of the need to create a real model to back it up. I spoke to soon. Please disregard :) From ben at benmabey.com Mon Jul 19 22:39:19 2010 From: ben at benmabey.com (Ben Mabey) Date: Mon, 19 Jul 2010 20:39:19 -0600 Subject: [rspec-users] How do I setup Rspec, Cucumber to test a Gem? In-Reply-To: References: Message-ID: <4C450C57.4080209@benmabey.com> Walther Diechmann wrote: > Hi, > > my question unwields me as a complete noob - which is okay - but I > apologize for this totally basic question <:) > > I've bought the PragProg Rspec Book and googled, been reading blogs and > what-have-I-not, but nowhere have I been able to find information > detailing how I setup a BDD environment for testing the construction of > a Gem. > > I have a ../gem_folder which I hope eventually will be a Gem to use with > Rails 3 and I really would like to upload it to GitHub with a good test > coverage. > > From the Rspec Book I've learned that within Rails Apps, I use Cucumber > and WebRat (among others) - but the book does not (or at least I?ve not > been able to discover it) show how to setup the environment, without the > Rails App. > > I guess my question could boil down to: how do I create the environment > (folders, files) to test a Gem meant to work with Rails? > > So far I have: > > ../gem_folder > ../gem_folder/features > ../gem_folder/lib > ../gem_folder/pkg > ../gem_folder/spec > > and a few files like Rakefile, Manifest, CHANGELOG, LICENSE - and I'm > able to push to Gemcutter and GitHub > > but where in this picture does the Rails App fit in? How do I make sure > that the Gem will work went installed/utilized on Rails App's > > best regards, > Walther > I like using jeweler to create the structure of my gems. It is like Rail's generators but for gems. Try it out: gem install jeweler jeweler my_gem --rspec --cucumber HTH, Ben From glenn.goodrich at gmail.com Mon Jul 12 05:18:17 2010 From: glenn.goodrich at gmail.com (Ruprict) Date: Mon, 12 Jul 2010 02:18:17 -0700 (PDT) Subject: [rspec-users] controller.should_receive(:render) problem Message-ID: <89f71ca7-303c-445e-a025-22e4faa50488@w31g2000yqb.googlegroups.com> Hi. My issue is similar to the one in this post: http://groups.google.com/group/rspec/browse_thread/thread/973d770e45bdd6cd/8ba067476003f08f?lnk=gst&q=render+controller+should_receive#8ba067476003f08f (which, btw, I could not reply to...only option was "Reply to Author") where I have a RESTful controller. I want create to redirect/render the new action if the model fails to save with the supplied form values. Pretty basic and typical stuff. In Rails, if I use redirect_to(new_my_model_path) then the entered values along with the error_messages on the object are lost and I can't re-fill the form or list the errors. If I use render :action => "new" then I keep all the request data and can use it to fill in form, etc. In my spec, if I use controller.should_receive(:render).with({:action=>"new"}) I get an expectation error that render is never called. This is true if I remove the .with() as well. If y'all could let me know either 1) Why my redirect_to vs render argument is flawed and/or 2) What I am doing wrong in the spec, I'd appreciate it. Thanks, Ruprict From tests.learner at gmail.com Mon Jul 12 13:35:43 2010 From: tests.learner at gmail.com (tests learner) Date: Mon, 12 Jul 2010 10:35:43 -0700 (PDT) Subject: [rspec-users] How it would be tested? Message-ID: <85af84d2-96db-4978-92ea-2519583569e0@b35g2000yqi.googlegroups.com> Hello all. I'm working with rails and came to a situation that i cannot imagine how to test this. Given i have an index action that retrieves me a collection of objects. But some of them have especific permissions. My index action act like this: - retrieve public objects. - retrieve permission 1 objects. - retrieve permission 2 objects. So i have to write 3 tests. it "should retrieve public objects" context "permission 1" it " should retrieve permission 1 objects" context "permission 2" it "should retrieve permission 2 objects" Until here no problems because only conditional tests and method calls. But how i would test the "Index.retrieve_objects_from_permission1" ? supose i have class Index < ActiveRecord::Base has_many :permissions def self.retrieve_objects_from_permission1 Index.all(:conditions => "permissions.id = 1", :include => :permissions) end def has_permission1 !self.permissions.find_by_id(1).nil? end end My Index.retrieve_objects_from_permission1 would be: it "should retrieve objects that have permission 1" do @collection = Index.retrieve_objects_from_permission1 @collection.each do |c| c.has_permission1.should == true end end Is it right? ( I didn't see it before on other's code, so i don't think it's right.) Sorry for my poor english. i hope I have been clear enough. Thank you :) From jayheaslip at gmail.com Mon Jul 19 08:51:52 2010 From: jayheaslip at gmail.com (Jay) Date: Mon, 19 Jul 2010 05:51:52 -0700 (PDT) Subject: [rspec-users] "bundle exec rspec" vs "rake spec" Message-ID: I'm in the process of upgrading my rails app to rails 3 and I'm getting different results from running the 2 commands above. The "bundle exec rspec" runs my tests correctly, but when I run "rake spec" it doesn't seem to do anything. I get "0 examples, 0 failures". This is on version 2.0.0.beta.17 of rspec. Any ideas on what I'm doing wrong? Thanks, Jay From trung at phamcom.com Mon Jul 19 14:49:36 2010 From: trung at phamcom.com (trung) Date: Mon, 19 Jul 2010 11:49:36 -0700 (PDT) Subject: [rspec-users] Event machine support Message-ID: <1549da62-a45f-414a-850f-f6e9eb093a6a@p11g2000prf.googlegroups.com> I have a question of how rspec treat eventmachined rails app. My understanding is eventmachined is normally run within Thin, and it is Thin who initiates the event loop. So how do you test the eventmachined rails app? Do we have to modify the rspec script to initiate the event loop? Thanks. From dchelimsky at gmail.com Tue Jul 20 07:37:08 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 20 Jul 2010 06:37:08 -0500 Subject: [rspec-users] "bundle exec rspec" vs "rake spec" In-Reply-To: References: Message-ID: <342CCDAA-E4A7-4146-8E91-A54008D6C51A@gmail.com> On Jul 19, 2010, at 7:51 AM, Jay wrote: > I'm in the process of upgrading my rails app to rails 3 and I'm > getting different results from running the 2 commands above. The > "bundle exec rspec" runs my tests correctly, but when I run "rake > spec" it doesn't seem to do anything. I get "0 examples, 0 > failures". This is on version 2.0.0.beta.17 of rspec. Any ideas on > what I'm doing wrong? Which beta version of rails are you on? Make sure that you've removed lib/tasks/rspec.rake and that rspec-rails listed in the :development group in your Gemfile. HTH, David > > Thanks, > Jay From dchelimsky at gmail.com Tue Jul 20 07:41:55 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 20 Jul 2010 06:41:55 -0500 Subject: [rspec-users] controller.should_receive(:render) problem In-Reply-To: <89f71ca7-303c-445e-a025-22e4faa50488@w31g2000yqb.googlegroups.com> References: <89f71ca7-303c-445e-a025-22e4faa50488@w31g2000yqb.googlegroups.com> Message-ID: <2FFC0AC9-18F9-4BC9-B9E4-6DFCAFF29848@gmail.com> On Jul 12, 2010, at 4:18 AM, Ruprict wrote: > Hi. > > My issue is similar to the one in this post: > http://groups.google.com/group/rspec/browse_thread/thread/973d770e45bdd6cd/8ba067476003f08f?lnk=gst&q=render+controller+should_receive#8ba067476003f08f > > (which, btw, I could not reply to...only option was "Reply to Author") > where I have a RESTful controller. I want create to redirect/render > the new action if the model fails to save with the supplied form > values. Pretty basic and typical stuff. > > In Rails, if I use > > redirect_to(new_my_model_path) > > then the entered values along with the error_messages on the object > are lost and I can't re-fill the form or list the errors. If I use > > render :action => "new" > > then I keep all the request data and can use it to fill in form, etc. > > In my spec, if I use > > controller.should_receive(:render).with({:action=>"new"}) > > I get an expectation error that render is never called. This is true > if I remove the .with() as well. > > If y'all could let me know either 1) Why my redirect_to vs render > argument is flawed and/or 2) What I am doing wrong in the spec, I'd > appreciate it. Please post the code in the failing spec and the new action, along with the backtrace of the error you're getting. Thx, David > > Thanks, > Ruprict From agresso at gmail.com Tue Jul 20 08:24:35 2010 From: agresso at gmail.com (Bogdan Gusiev) Date: Tue, 20 Jul 2010 15:24:35 +0300 Subject: [rspec-users] [Rspec-Rails] before(:all) doesn't rollback Message-ID: I don't if this is a bug or feature but if before(:all) create some persistent objects, these changes doesn't rollback when we get out of the context. Here are simplest example to see the issue: describe Person do context "1" do before(:all) do Person.create!(@valid_attributes) end it { Person.count.should == 1 } end context "2" do before(:all) do Person.create!(@valid_attributes) end it { Person.count.should == 1 } end end One of these two examples always fail because the object created in before(:all) block of other example won't be clean up. If it is not a bug then can someone explain why does it work in this way? My thoughts is that changes made by before(:all) should be rollback after we get out of scope. In the same way as before(:each) do. -- Bogdan Gusiev. agresso at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at ruby-forum.com Tue Jul 20 08:57:34 2010 From: lists at ruby-forum.com (Walther Diechmann) Date: Tue, 20 Jul 2010 14:57:34 +0200 Subject: [rspec-users] How do I setup Rspec, Cucumber to test a Gem? In-Reply-To: <4C450C57.4080209@benmabey.com> References: <4C450C57.4080209@benmabey.com> Message-ID: <79902858af6245abc5a0b441b102ed69@ruby-forum.com> Ben Mabey wrote: > I like using jeweler to create the structure of my gems. It is like > Rail's generators but for gems. Try it out: > > gem install jeweler > jeweler my_gem --rspec --cucumber > > > HTH, > Ben not really - but thanks for offering help <:) I followed the Rspec Book, railscast's on the subject and used echoe and jeweller and had myself a genuine push'able Gem - but as my question was: how for Pete's sake am I going to be able to test Rails Controllers and Rails Models? (even tried reading the rspec-rails gem as suggested by matt wynne - and implementing parts from that. I partly see where dchelimsky is going, but it's just to complex to me, alas) - anyways, I'm on my 4th day on this gem-quest - and about to fold and walk away with the knowledge that testing is just a tad out of my league <:/ But - thanks a bunch for trying to steer me afloat :) /Walther -- Posted via http://www.ruby-forum.com/. From cdemyanovich at gmail.com Tue Jul 20 09:10:51 2010 From: cdemyanovich at gmail.com (Craig Demyanovich) Date: Tue, 20 Jul 2010 09:10:51 -0400 Subject: [rspec-users] [Rspec-Rails] before(:all) doesn't rollback In-Reply-To: References: Message-ID: More info here . Note the warning at the bottom of the page. Regards, Craig -------------- next part -------------- An HTML attachment was scrubbed... URL: From rogerpack2005 at gmail.com Tue Jul 20 14:07:43 2010 From: rogerpack2005 at gmail.com (rogerdpack) Date: Tue, 20 Jul 2010 11:07:43 -0700 (PDT) Subject: [rspec-users] methods not available... Message-ID: <8001dc20-25c9-4b32-b03f-1817e44094e5@t13g2000prf.googlegroups.com> Hi all. Noticed that with rspec 1.x methods at "higher levels" aren't available in lower, ex: context "a" do def go end it "should pass" do go end it "should pass again" do context "a::b" do go end end end This surprised me a bit, making re-use of outer methods unavailable. Is it expected? Thanks! -r From dchelimsky at gmail.com Tue Jul 20 14:42:29 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 20 Jul 2010 13:42:29 -0500 Subject: [rspec-users] methods not available... In-Reply-To: <8001dc20-25c9-4b32-b03f-1817e44094e5@t13g2000prf.googlegroups.com> References: <8001dc20-25c9-4b32-b03f-1817e44094e5@t13g2000prf.googlegroups.com> Message-ID: <9E95F563-0C0C-4E43-B4B5-FAB71D123668@gmail.com> On Jul 20, 2010, at 1:07 PM, rogerdpack wrote: > Hi all. Noticed that with rspec 1.x > > methods at "higher levels" aren't available in lower, ex: > > context "a" do > def go > end > > it "should pass" do > go > end > > it "should pass again" do > context "a::b" do You can't wrap contexts inside examples. This should work: describe "a" do def go; end context "b" do it "should access go" do go end end end HTH, David > go > end > end > > end > > This surprised me a bit, making re-use of outer methods unavailable. > Is it expected? > > Thanks! > -r > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From peter.fitzgibbons at gmail.com Tue Jul 20 17:18:01 2010 From: peter.fitzgibbons at gmail.com (Peter Fitzgibbons) Date: Tue, 20 Jul 2010 16:18:01 -0500 Subject: [rspec-users] spec w/o db:test:prepare Message-ID: <4C461289.8040504@gmail.com> HI All, I would like to perform my spec runs without the db:test:prepare rake prereq. It would be nice if I could alter spec to prereq db:test:purge only. Could you give me some advice/urls/pointers on how best to go about this? Thanks, Peter Fitzgibbons (847) 859-9550 Email: peter.fitzgibbons at gmail.com IM GTalk: peter.fitzgibbons IM AOL: peter.fitzgibbons at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Tue Jul 20 19:40:41 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 20 Jul 2010 18:40:41 -0500 Subject: [rspec-users] spec w/o db:test:prepare In-Reply-To: <4C461289.8040504@gmail.com> References: <4C461289.8040504@gmail.com> Message-ID: <0289065A-537D-4153-9A0A-84A0039E2A26@gmail.com> On Jul 20, 2010, at 4:18 PM, Peter Fitzgibbons wrote: > HI All, > > I would like to perform my spec runs without the db:test:prepare rake prereq. > It would be nice if I could alter spec to prereq db:test:purge only. > > Could you give me some advice/urls/pointers on how best to go about this? Rake::Task[:spec].clear_prerequisites task :spec => ["db:test:purge"] Cheers, David From dchelimsky at gmail.com Tue Jul 20 19:50:26 2010 From: dchelimsky at gmail.com (dchelimsky at gmail.com) Date: Tue, 20 Jul 2010 16:50:26 -0700 (PDT) Subject: [rspec-users] rspec2 help output has brackets? In-Reply-To: <4A4F5511-0E82-4A52-94C3-859F8BC6CCD3@wincent.com> References: <4116B95B-7E55-4871-99F1-F9ACA1D55B29@gmail.com> <4A4F5511-0E82-4A52-94C3-859F8BC6CCD3@wincent.com> Message-ID: <54f29d59-8da9-4631-9857-2114ce7d170a@d16g2000yqb.googlegroups.com> On Jul 19, 9:20?am, Wincent Colaiuta wrote: > El 19/07/2010, a las 15:52, David Chelimsky escribi?: > > > > > > > On Jul 19, 2010, at 8:17 AM, rogerdpack wrote: > > >> Hi all. > > >> Saw this: > > >> Usage: rspec [options] [files or directories] > >> ? -b, --backtrace ? ? ? ? ? ? ? ? ?Enable full backtrace > >> ? -c, --[no-]color, --[no-]colour ?Enable color in the output > >> ? -d, --debug ? ? ? ? ? ? ? ? ? ? ?Enable debugging > >> ? -e, --example PATTERN ? ? ? ? ? ?Run examples whose full > >> descriptions match this pattern > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(PATTERN is compiled into a Ruby > >> regular expression) > >> ? -f, --format FORMATTER ? ? ? ? ? Choose a formatter > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[p]rogress (default - dots) > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[d]ocumentation (group and > >> example names) > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[h]tml > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?[t]extmate > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?custom formatter class name > > >> tried this: > >> $ rspec -fp (for the [p] in [p]rogress) > > >> got this: > > >> Exception `ArgumentError' at c:/dev/ruby/downloads/jruby/lib/ruby/gems/ > >> 1.8/gems/rspec-core-2.0.0.beta.17/lib/rspec/core/configuration.rb:191 > >> - Formatter 'p' unknown - maybe you meant 'documentation' or > >> 'progress'?. > >> c:/dev/ruby/downloads/jruby/lib/ruby/gems/1.8/gems/rspec- > >> core-2.0.0.beta.17/lib/rspec/core/configuration.rb:191:in > >> `formatter=': Formatter 'p' unknown - maybe you meant 'documentation' > >> or 'progress'?. (ArgumentError) > > >> is this expected? > > > Nope. Bug. rspec-core bugs go here:http://github.com/rspec/rspec-core/issues > > In the meantime, "rspec -f p" (with a space) works fine. Fixed: http://github.com/rspec/rspec-core/issues/closed#issue/84 > > Wincent > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From rogerpack2005 at gmail.com Tue Jul 20 21:05:58 2010 From: rogerpack2005 at gmail.com (rogerdpack) Date: Tue, 20 Jul 2010 18:05:58 -0700 (PDT) Subject: [rspec-users] Event machine support In-Reply-To: <1549da62-a45f-414a-850f-f6e9eb093a6a@p11g2000prf.googlegroups.com> References: <1549da62-a45f-414a-850f-f6e9eb093a6a@p11g2000prf.googlegroups.com> Message-ID: <3f3507b0-8aab-4801-af01-fe357ea36659@i19g2000pro.googlegroups.com> > My understanding is eventmachined is normally run within Thin, and it > is Thin who initiates the event loop. > > So how do you test the eventmachined rails app? Do we have to modify > the rspec script to initiate the event loop? You could also use before(:all) do EM.start_in_other_thread end or what not. I would probably ping the EM group. From rogerpack2005 at gmail.com Tue Jul 20 21:05:18 2010 From: rogerpack2005 at gmail.com (rogerdpack) Date: Tue, 20 Jul 2010 18:05:18 -0700 (PDT) Subject: [rspec-users] methods not available... In-Reply-To: <9E95F563-0C0C-4E43-B4B5-FAB71D123668@gmail.com> References: <8001dc20-25c9-4b32-b03f-1817e44094e5@t13g2000prf.googlegroups.com> <9E95F563-0C0C-4E43-B4B5-FAB71D123668@gmail.com> Message-ID: <679ef59e-7c2c-42da-81dd-3257dd613841@w35g2000prd.googlegroups.com> > > ?it "should pass again" do > > ? context "a::b" do > > You can't wrap contexts inside examples. Cool thanks for the reply. The confusing part is that it allowed me to have that context within an example. Maybe a more explicit failure for newbies when they do this would be kind. -r From lists at ruby-forum.com Wed Jul 21 02:41:56 2010 From: lists at ruby-forum.com (Zhenning Guan) Date: Wed, 21 Jul 2010 08:41:56 +0200 Subject: [rspec-users] [rails] shoud I test validate_presentence_of series? Message-ID: Suppose I have a model Forum, have some attributes, title, content, tag.so I do it in Forum model. validates_presence_of :title validates_presence_of :tag validates_presence_of :content. when I added validateds_presence_of, rails will restrict the attribute not be empty, when save record. so after that, Do I still need to test those attributs not_valid? like this it 'should not be valid when title empty' do Forum.new(empty_title_attrbiute_hash).should_not be_valid end it 'should not be valid when tag empty' do Forum.new(empty_tag_attrbiute_hash).should_not be_valid end it 'should not be valid when content empty' do Forum.new(empty_content_attrbiute_hash).should_not be_valid end -- Posted via http://www.ruby-forum.com/. From cdemyanovich at gmail.com Wed Jul 21 07:33:22 2010 From: cdemyanovich at gmail.com (Craig Demyanovich) Date: Wed, 21 Jul 2010 07:33:22 -0400 Subject: [rspec-users] [rails] shoud I test validate_presentence_of series? In-Reply-To: References: Message-ID: I like covering validation with RSpec instead of only relying on it being covered at a higher level. I like to check for error(s) on each attribute to be sure that the model is not invalid for some other reason. Here's how I do it: describe Forum, 'being valid' do it "requires a name" do forum = Forum.new(:title => nil) forum.should_not be_valid forum.should have_at_least(1).error_on(:title) end it "requires a code" do forum = Forum.new(:tag => nil) forum.should_not be_valid forum.should have_at_least(1).error_on(:tag) end it "requires content" do forum = Forum.new(:content => nil) forum.should_not be_valid forum.should have_at_least(1).error_on(:content) end end Note that, in this example, you can put all of your validates_presence_of declarations on one line. validates_presence_of :title, :tag, :content Regards, Craig -------------- next part -------------- An HTML attachment was scrubbed... URL: From phillipkoebbe at gmail.com Wed Jul 21 09:08:48 2010 From: phillipkoebbe at gmail.com (Phillip Koebbe) Date: Wed, 21 Jul 2010 08:08:48 -0500 Subject: [rspec-users] [rails] shoud I test validate_presentence_of series? In-Reply-To: References: Message-ID: <4C46F160.7040403@gmail.com> On 2010-07-21 1:41 AM, Zhenning Guan wrote: > Suppose I have a model Forum, have some attributes, title, content, > tag.so I do it in Forum model. > validates_presence_of :title > validates_presence_of :tag > validates_presence_of :content. > > > when I added validateds_presence_of, rails will restrict the attribute > not be empty, when save record. so after that, Do I still need to test > those attributs not_valid? > > like this > > it 'should not be valid when title empty' do > Forum.new(empty_title_attrbiute_hash).should_not be_valid > end > > it 'should not be valid when tag empty' do > Forum.new(empty_tag_attrbiute_hash).should_not be_valid > end > > it 'should not be valid when content empty' do > Forum.new(empty_content_attrbiute_hash).should_not be_valid > end Something else to keep in mind is that in the spirit of BDD, ideally you are writing your specs before you write any of your code. So to write examples that specify attributes cannot be nil will come before the validates_presence_of statements in your model. Then when your tests pass, you know you've implemented the correct functionality. This is also a great sanity check when, later down the line, something gets accidentally changed or deleted in the model and you have a spec to catch it. Peace, Phillip From apremdas at gmail.com Wed Jul 21 11:09:31 2010 From: apremdas at gmail.com (Andrew Premdas) Date: Wed, 21 Jul 2010 16:09:31 +0100 Subject: [rspec-users] 'its' not working Message-ID: trying out new syntax from jon larkowski's rspec presentation. Following doesn't work in that when I run the line from the command prompt or from textmate no specs are run context "cancel" do subject do order = at_dropshipping order.cancel_dropship! order end its(:status) { should == 'waiting_for_shipping' } # doesn't work end spec --version rspec 1.3.0 tia Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Wed Jul 21 12:06:50 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 21 Jul 2010 11:06:50 -0500 Subject: [rspec-users] 'its' not working In-Reply-To: References: Message-ID: On Jul 21, 2010, at 10:09 AM, Andrew Premdas wrote: > trying out new syntax from jon larkowski's rspec presentation. Following doesn't work in that when I run the line from the command prompt or from textmate no specs are run > > > context "cancel" do > subject do > order = at_dropshipping > order.cancel_dropship! > order > end > > its(:status) { should == 'waiting_for_shipping' } # doesn't work > end > > spec --version rspec 1.3.0 Please post the entire spec in question, the command you are using to run it, and all of the output you are seeing when you try to run it. Thx > > tia > > Andrew From costa at mouldwarp.com Wed Jul 21 15:58:21 2010 From: costa at mouldwarp.com (Costa Shapiro) Date: Wed, 21 Jul 2010 15:58:21 -0400 Subject: [rspec-users] Data-wise context combination for controller speccing In-Reply-To: <4A09A2AF-061C-4C30-A50B-0D47762C25B2@wincent.com> References: <66E9A625-5EF8-4A82-94EE-8EB2A8848DA5@mattwynne.net> <327DFD8F-7A09-49B5-B985-328A77DF0876@wincent.com> <4C445F42.2050305@gmail.com> <4A09A2AF-061C-4C30-A50B-0D47762C25B2@wincent.com> Message-ID: Thank you very much for your valuable feedback. First, the example is a toy example of course, while the idea of mixing-matching contexts is not. Note that it would be a totally backward-compatible enhancement to rspec, and that a developer would still be in full control of what gets mixed-matched. Then, the subject might been confusing (not to mention the unsuccessful suggested syntax), as the idea is not necessarily coupled with data permutations. I accept the criticism about over-mocking, and even more than that, I find mocking AR extremely tedious, that's why I've initially thought of coming up with something like http://github.com/costa/rspec-orm (there will be a separate mail on that, please don't comment it here just yet). I hope I'll bring some sort of POC -- which will be working for me at least -- soon. Any comments or suggestions are more than welcome. Cheers, Costa. On 19 July 2010 11:12, Wincent Colaiuta wrote: > El 19/07/2010, a las 16:20, Phillip Koebbe escribi?: > > > On 2010-07-19 5:38 AM, Wincent Colaiuta wrote: > >> I don't necessarily think so. Matt says you can probably do this right > now by using macros. I don't actually know what he means by that, but I do > know that there are cases where I sometimes want a bunch of nearly identical > specs, and I generate them in code using enumeration or some other means; > ie. dumb example: > >> > >> [:foo, :bar, :baz].do |thing| > >> describe "#{thing} dimensions" do > >> it 'has length' do > >> thing.to_s.length.should> 0 > >> end > >> end > >> end > >> > > > > Glad to see I'm not the only one that does this. :) > > Yeah, I think it's a legitimate technique, as long as you don't get too > carried away with it. > > I use it, for example, for some code quality specs: > > Wincent::SOURCE_FILES.each do |file| > describe file do > it 'contains no trailing whitespace' do > file.should_not have_trailing_whitespace > end > > it 'contains no tabs' do > file.should_not contain_tabs > end > > it 'has a newline at the end' do > file.should have_newline_at_end_of_file > end > end > end > > Cheers, > Wincent > > > _______________________________________________ > 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 costa at mouldwarp.com Wed Jul 21 16:24:01 2010 From: costa at mouldwarp.com (Costa Shapiro) Date: Wed, 21 Jul 2010 16:24:01 -0400 Subject: [rspec-users] How it would be tested? In-Reply-To: <85af84d2-96db-4978-92ea-2519583569e0@b35g2000yqi.googlegroups.com> References: <85af84d2-96db-4978-92ea-2519583569e0@b35g2000yqi.googlegroups.com> Message-ID: Dear Mr. Learner, Please note that while very similar in functionality, specs' philosophy differs from tests' (especially from non-TDD ones). That is, you write spec first, see it fail, and write some code to make it pass. If you happen to write any implementation code first, you should disregard it while writing a spec. You may find BDD reading in abundance on the internets. To get a more substantial reply, I think you might want to describe what you want your code to do in plain English, and the community will hopefully help you to express that in rspec. Cheers, Costa. On 12 July 2010 13:35, tests learner wrote: > Hello all. > > I'm working with rails and came to a situation that i cannot imagine > how to test this. > > Given i have an index action that retrieves me a collection of > objects. > But some of them have especific permissions. > > > My index action act like this: > - retrieve public objects. > - retrieve permission 1 objects. > - retrieve permission 2 objects. > > So i have to write 3 tests. > > it "should retrieve public objects" > > context "permission 1" > it " should retrieve permission 1 objects" > context "permission 2" > it "should retrieve permission 2 objects" > > > Until here no problems because only conditional tests and method > calls. > > But how i would test the "Index.retrieve_objects_from_permission1" ? > > supose i have > > class Index < ActiveRecord::Base > has_many :permissions > def self.retrieve_objects_from_permission1 > Index.all(:conditions => "permissions.id = 1", :include > => :permissions) > end > > def has_permission1 > !self.permissions.find_by_id(1).nil? > end > end > > > My Index.retrieve_objects_from_permission1 would be: > > it "should retrieve objects that have permission 1" do > @collection = Index.retrieve_objects_from_permission1 > @collection.each do |c| > c.has_permission1.should == true > end > end > > Is it right? ( I didn't see it before on other's code, so i don't > think it's right.) > > > Sorry for my poor english. i hope I have been clear enough. > > > Thank you :) > _______________________________________________ > 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 peter.fitzgibbons at gmail.com Wed Jul 21 16:32:15 2010 From: peter.fitzgibbons at gmail.com (Peter Fitzgibbons) Date: Wed, 21 Jul 2010 15:32:15 -0500 Subject: [rspec-users] spec w/o db:test:prepare In-Reply-To: <0289065A-537D-4153-9A0A-84A0039E2A26@gmail.com> References: <4C461289.8040504@gmail.com> <0289065A-537D-4153-9A0A-84A0039E2A26@gmail.com> Message-ID: How 'bout for rspec2? BTW: Where should these magic lines be placed? Inside a ./config/initializers/my_init.rb ?? Peter Fitzgibbons (847) 859-9550 Email: peter.fitzgibbons at gmail.com IM GTalk: peter.fitzgibbons IM AOL: peter.fitzgibbons at gmail.com On Tue, Jul 20, 2010 at 6:40 PM, David Chelimsky wrote: > On Jul 20, 2010, at 4:18 PM, Peter Fitzgibbons wrote: > > > HI All, > > > > I would like to perform my spec runs without the db:test:prepare rake > prereq. > > It would be nice if I could alter spec to prereq db:test:purge only. > > > > Could you give me some advice/urls/pointers on how best to go about this? > > Rake::Task[:spec].clear_prerequisites > task :spec => ["db:test:purge"] > > 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 Wed Jul 21 17:17:51 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 21 Jul 2010 16:17:51 -0500 Subject: [rspec-users] spec w/o db:test:prepare In-Reply-To: References: <4C461289.8040504@gmail.com> <0289065A-537D-4153-9A0A-84A0039E2A26@gmail.com> Message-ID: <82F16374-3629-4D05-A282-9E20490508E1@gmail.com> On Jul 21, 2010, at 3:32 PM, Peter Fitzgibbons wrote: > On Tue, Jul 20, 2010 at 6:40 PM, David Chelimsky wrote: > On Jul 20, 2010, at 4:18 PM, Peter Fitzgibbons wrote: > > > HI All, > > > > I would like to perform my spec runs without the db:test:prepare rake prereq. > > It would be nice if I could alter spec to prereq db:test:purge only. > > > > Could you give me some advice/urls/pointers on how best to go about this? > > Rake::Task[:spec].clear_prerequisites > task :spec => ["db:test:purge"] > How 'bout for rspec2? Should work the same way. > > BTW: Where should these magic lines be placed? Inside a ./config/initializers/my_init.rb ?? In any .rake file in lib/tasks (those should get loaded after the ones in the gems) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Wed Jul 21 17:19:03 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 21 Jul 2010 16:19:03 -0500 Subject: [rspec-users] spec w/o db:test:prepare In-Reply-To: <82F16374-3629-4D05-A282-9E20490508E1@gmail.com> References: <4C461289.8040504@gmail.com> <0289065A-537D-4153-9A0A-84A0039E2A26@gmail.com> <82F16374-3629-4D05-A282-9E20490508E1@gmail.com> Message-ID: <935850CF-7164-4084-8B4A-5EC5646E6876@gmail.com> On Jul 21, 2010, at 4:17 PM, David Chelimsky wrote: > On Jul 21, 2010, at 3:32 PM, Peter Fitzgibbons wrote: >> On Tue, Jul 20, 2010 at 6:40 PM, David Chelimsky wrote: >> On Jul 20, 2010, at 4:18 PM, Peter Fitzgibbons wrote: >> >> > HI All, >> > >> > I would like to perform my spec runs without the db:test:prepare rake prereq. >> > It would be nice if I could alter spec to prereq db:test:purge only. >> > >> > Could you give me some advice/urls/pointers on how best to go about this? >> >> Rake::Task[:spec].clear_prerequisites >> task :spec => ["db:test:purge"] > >> How 'bout for rspec2? > > Should work the same way. > >> >> BTW: Where should these magic lines be placed? Inside a ./config/initializers/my_init.rb ?? > > In any .rake file in lib/tasks (those should get loaded after the ones in the gems) Also - there's no magic about these lines. Standard Ruby/rake - no metaprogramming, nothing mysterious. Just gotta know how Rake works. -------------- next part -------------- An HTML attachment was scrubbed... URL: From costa at mouldwarp.com Wed Jul 21 17:28:02 2010 From: costa at mouldwarp.com (Costa Shapiro) Date: Wed, 21 Jul 2010 17:28:02 -0400 Subject: [rspec-users] rspec-orm and _not_ mocking models Message-ID: Hello, (Surprisingly?) I find mocking AR (DM less so) in specs extremely tedious _and_ intrusive. Having said this, I find the approach of top-down VCM speccing very legitimate (cucumber for V, rspec for C, and probably unit tests for M). That is, a model is an inherent though separate part of the controller and trying to spec just the controller lacks efficiency (pragmatism) and leads to frustration. Therefore, I've starting working on http://github.com/costa/rspec-orm(everything is of concept-quality there, including the name). It's already "working for me". I think the README there pretty much cuts it, so I'd just welcome the comments here. Note that ? I'm sorry ? the code is not only unpackaged, but it is in a separate http://github.com/costa/dev/tree/master/ruby/ in part (for a reason). Again, *any* feedback is appreciated. Cheers, Costa. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at ruby-forum.com Wed Jul 21 21:30:18 2010 From: lists at ruby-forum.com (Zhenning Guan) Date: Thu, 22 Jul 2010 03:30:18 +0200 Subject: [rspec-users] [rails] shoud I test validate_presentence_of series? In-Reply-To: <4C46F160.7040403@gmail.com> References: <4C46F160.7040403@gmail.com> Message-ID: thank you all. :) -- Posted via http://www.ruby-forum.com/. From tests.learner at gmail.com Wed Jul 21 22:41:34 2010 From: tests.learner at gmail.com (tests learner) Date: Wed, 21 Jul 2010 19:41:34 -0700 (PDT) Subject: [rspec-users] How it would be tested? In-Reply-To: References: <85af84d2-96db-4978-92ea-2519583569e0@b35g2000yqi.googlegroups.com> Message-ID: Costa Shapiro, Thank you for paying atention. But How i would write if i don't know nothing about the code ? My problem is: I have a messages listing section that will differ according of type of user and according with message permission. I have messages that are public and private. Anyone can see public messages. The private messages only can be accessed by who participate on them and users that have Owner role on system. How it would be tested ? Since my listing have to list: if user not owner: - public messages + messages that the user can view because he participate on them if user is owner: - all messages. So i think the behavior that i have to spec is: context "guests" do (for ex.) before(:all) do #mock a guest here end it "should see all public messages" it "should see all messages that participate" end context "owners" do before(:all) do #mock a owner here end it "should see all messages" end Right? I'll be grateful, if you could give any hint about the spec code. Greets, On 21 jul, 17:24, Costa Shapiro wrote: > Dear Mr. Learner, > > Please note that while very similar in functionality, specs' philosophy > differs from tests' (especially from non-TDD ones). > That is, you write spec first, see it fail, and write some code to make it > pass. > If you happen to write any implementation code first, you should disregard > it while writing a spec. > You may find BDD reading in abundance on the internets. > > To get a more substantial reply, I think you might want to describe what you > want your code to do in plain English, and the community will hopefully help > you to express that in rspec. > > Cheers, > Costa. > > On 12 July 2010 13:35, tests learner wrote: > > > Hello all. > > > I'm working with rails and came to a situation that i cannot imagine > > how to test this. > > > Given i have an index action that retrieves me a collection of > > objects. > > But some of them have especific permissions. > > > My index action act like this: > > - retrieve public objects. > > - retrieve permission 1 objects. > > - retrieve permission 2 objects. > > > So i have to write 3 tests. > > > it "should retrieve public objects" > > > context "permission 1" > > ?it " should retrieve permission 1 objects" > > context "permission 2" > > ?it "should retrieve permission 2 objects" > > > Until here no problems because only conditional tests and method > > calls. > > > But how i would test the "Index.retrieve_objects_from_permission1" ? > > > supose i have > > > class ?Index < ActiveRecord::Base > > ? has_many :permissions > > ? def self.retrieve_objects_from_permission1 > > ? ? ? Index.all(:conditions => "permissions.id = 1", :include > > => :permissions) > > ? end > > > ? ?def has_permission1 > > ? ? ? !self.permissions.find_by_id(1).nil? > > ? ?end > > end > > > My Index.retrieve_objects_from_permission1 would be: > > > it "should retrieve objects that have permission 1" do > > ? @collection = Index.retrieve_objects_from_permission1 > > ? @collection.each do |c| > > ? ? ? c.has_permission1.should == true > > ? ?end > > end > > > Is it right? ( I didn't see it before on other's code, so i don't > > think it's right.) > > > Sorry for my poor english. i hope I have been clear enough. > > > Thank you :) > > _______________________________________________ > > rspec-users mailing list > > rspec-us... at rubyforge.org > >http://rubyforge.org/mailman/listinfo/rspec-users > > > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From apremdas at gmail.com Thu Jul 22 05:09:14 2010 From: apremdas at gmail.com (Andrew Premdas) Date: Thu, 22 Jul 2010 10:09:14 +0100 Subject: [rspec-users] 'its' not working In-Reply-To: References: Message-ID: On 21 July 2010 17:06, David Chelimsky wrote: > On Jul 21, 2010, at 10:09 AM, Andrew Premdas wrote: > > > trying out new syntax from jon larkowski's rspec presentation. Following > doesn't work in that when I run the line from the command prompt or from > textmate no specs are run > > > > > > context "cancel" do > > subject do > > order = at_dropshipping > > order.cancel_dropship! > > order > > end > > > > its(:status) { should == 'waiting_for_shipping' } # doesn't work > > end > > > > spec --version rspec 1.3.0 > > Please post the entire spec in question, the command you are using to run > it, and all of the output you are seeing when you try to run it. > > Thx > > > > > tia > > > > Andrew > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > Found out that I can get :its working in my general environment, so maybe I am doing something wrong in this specific spec. I won't post the whole spec for now, as its massive. Instead I will try and narrow down the problem and post back if I find anything. In the meantime, thanks for your help Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: From ericmilford at gmail.com Thu Jul 22 11:48:27 2010 From: ericmilford at gmail.com (ericindc) Date: Thu, 22 Jul 2010 08:48:27 -0700 (PDT) Subject: [rspec-users] should_receive test unexpectedly failing Message-ID: <77b22574-4574-4a6e-ba4e-4b1f4bbc9136@w30g2000yqw.googlegroups.com> I'm unsure why this test is still failing. I've tested it in console and the code works as expected. Is there something wrong with how I have my test written? ****************** error 1) Job selecting the next job to be processed should lock the next job Failure/Error: job.should_receive(:update_attribute).with(:locked, true) (#).update_attribute(:locked, true) expected: 1 time received: 0 times ****************** job_spec.rb it "should lock the next job" do job = Factory(:job, :locked => false) job.should_receive(:update_attribute).with(:locked, true) Job.next end ****************** job.rb def self.next job = incomplete.unlocked.prioritized.limit(1).first job.lock! if job job end def lock! update_attribute(:locked, true) end def unlock! update_attribute(:locked, false) end From dchelimsky at gmail.com Thu Jul 22 12:03:56 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 22 Jul 2010 11:03:56 -0500 Subject: [rspec-users] should_receive test unexpectedly failing In-Reply-To: <77b22574-4574-4a6e-ba4e-4b1f4bbc9136@w30g2000yqw.googlegroups.com> References: <77b22574-4574-4a6e-ba4e-4b1f4bbc9136@w30g2000yqw.googlegroups.com> Message-ID: On Jul 22, 2010, at 10:48 AM, ericindc wrote: > I'm unsure why this test is still failing. I've tested it in console > and the code works as expected. Is there something wrong with how I > have my test written? > > ****************** error > > 1) Job selecting the next job to be processed should lock the next job > Failure/Error: job.should_receive(:update_attribute).with(:locked, > true) > (#).update_attribute(:locked, true) > expected: 1 time > received: 0 times > > > ****************** job_spec.rb > > it "should lock the next job" do > job = Factory(:job, :locked => false) > job.should_receive(:update_attribute).with(:locked, true) > Job.next > end > > > ****************** job.rb > > def self.next > job = incomplete.unlocked.prioritized.limit(1).first This job object is not the same object as the on in the spec. To get this to work, you'd have to stub like so: Job.stub_chain(:incomplete, :unlocked, :prioritized, :limit).and_return(job) Personally, I wouldn't bother, especially since you're using a real db backed object anyhow (Factory(:job ...)). I'd just write the spec like this: job = Factory(:job, :locked => false) job.next job.should_not be_locked Much cleaner and to the point, and less invasive (and therefore less brittle). HTH, David > job.lock! if job > job > end > > def lock! > update_attribute(:locked, true) > end > > def unlock! > update_attribute(:locked, false) > end > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From ashley.moran at patchspace.co.uk Fri Jul 23 03:09:39 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Fri, 23 Jul 2010 08:09:39 +0100 Subject: [rspec-users] Parameterised shared examples / metadata in examples (RSpec 2) Message-ID: <7854C363-C02F-45DA-8296-32051F12E16B@patchspace.co.uk> Hi Warning: this goes on quite a bit. It contains early-morning caffeinated ramblings and many "hmmm I wonder what this does..." snippets. I'm looking for the best way to parameterise shared examples. Imagine (as an academic example...) you were doing it for subclasses of Struct instances (a more realistic example might be ActiveRecord subclasses, or DataMapper resources), such as: class MyStruct < Struct.new(:a, :b) end class MyOtherStruct < Struct.new(:foo, :bar) end I've seen it done with #let, eg: shared_examples_for "a Struct" do it "has methods" do properties.each do |property| struct.should respond_to(property) end end end describe MyStruct do let(:struct) { MyStruct.new } let(:properties) { [:a, :b] } it_should_behave_like "a Struct" end describe MyOtherStruct do let(:struct) { MyOtherStruct.new } let(:properties) { [:foo, :bar] } it_should_behave_like "a Struct" end Which is not a bad solution, but does feel a bit too much like using (scoped) global variables for my liking. There's no explicit association between the shared examples and their parameters (and the arguments actually passed in each example group. So I started to wonder if this could be done with metadata. My first naive stab was this: describe MyStruct do it_should_behave_like "a Struct", properties: [:a, :b] end But this fails: Could not find shared example group named {:properties=>[:a, :b]} Anyway, I dug in a bit and found that the metadata is only available to the example group anyway, not the examples themselves. So you can't do: describe MyStruct, properties: [:a, :b] do let(:struct) { MyStruct.new } it "has methods" do metadata[:properties].each do |property| struct.should respond_to(property) end end end But (more digging), you can do this: describe MyStruct, properties: [:a, :b] do let(:struct) { MyStruct.new } it "has methods" do example.metadata[:properties].each do |property| struct.should respond_to(property) end end end Which means I can get this close to my original dreamed-up syntax: shared_examples_for "a Struct with metadata" do it "has methods" do example.metadata[:properties].each do |property| struct.should respond_to(property) end end end describe MyStruct, properties: [:a, :b] do let(:struct) { MyStruct.new } it_should_behave_like "a Struct with metadata" end I don't object so much to having "struct" floating around, as it's fairly safe to say all the shared examples will depend on #struct being available. Although, arguably, #subject would be better: shared_examples_for "a subject Struct with metadata" do it "has methods" do example.metadata[:properties].each do |property| subject.should respond_to(property) end end end describe MyStruct, properties: [:a, :b] do subject { MyStruct.new } it_should_behave_like "a subject Struct with metadata" end or even: shared_examples_for "a subject Struct with metadata" do metadata[:properties].each do |property| it { should respond_to(property) } end end describe MyStruct, properties: [:a, :b] do subject { MyStruct.new } it_should_behave_like "a subject Struct with metadata" end I tried to be a bit clever to see if I could clean up the example definitions in the shared spec, but I got this far before hitting weirdness that was beyond my understanding of RSpec (and the reach of my spade...). But, this was a bit of a tangent anyway: shared_examples_for "a subject Struct with metadata" do metadata[:params].each { |key, value| define_method(key) { value } } p self.inspect # outputs nil (!!!) properties.each do |property| it { should respond_to(property) } end end describe MyStruct, params: {properties: [:a, :b]} do subject { MyStruct.new } it_should_behave_like "a subject Struct with metadata" end Sooooo... after all this, I just wondered if anyone had any ideas what the best way to achieve this is, and how it could be extended. For example, would there be any merit in being able to write: it_should_behave_like "a Struct", properties: [:a, :b] ? Also I figure that as the metadata system is new, it's potentially unfinished and/or in flux. What are the plans/intentions/opportunities for expansion for it? Cheers Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From win at wincent.com Fri Jul 23 03:57:36 2010 From: win at wincent.com (Wincent Colaiuta) Date: Fri, 23 Jul 2010 09:57:36 +0200 Subject: [rspec-users] Parameterised shared examples / metadata in examples (RSpec 2) In-Reply-To: <7854C363-C02F-45DA-8296-32051F12E16B@patchspace.co.uk> References: <7854C363-C02F-45DA-8296-32051F12E16B@patchspace.co.uk> Message-ID: <930905AA-123D-46E1-A7F5-74C6AA1618B3@wincent.com> El 23/07/2010, a las 09:09, Ashley Moran escribi?: > I'm looking for the best way to parameterise shared examples. Imagine (as an academic example...) you were doing it for subclasses of Struct instances (a more realistic example might be ActiveRecord subclasses, or DataMapper resources), such as: > > class MyStruct < Struct.new(:a, :b) > end > > class MyOtherStruct < Struct.new(:foo, :bar) > end > > > I've seen it done with #let, eg: > > shared_examples_for "a Struct" do > it "has methods" do > properties.each do |property| > struct.should respond_to(property) > end > end > end > > describe MyStruct do > let(:struct) { MyStruct.new } > let(:properties) { [:a, :b] } > it_should_behave_like "a Struct" > end > > describe MyOtherStruct do > let(:struct) { MyOtherStruct.new } > let(:properties) { [:foo, :bar] } > it_should_behave_like "a Struct" > end > > Which is not a bad solution, but does feel a bit too much like using (scoped) global variables for my liking. There's no explicit association between the shared examples and their parameters (and the arguments actually passed in each example group. Recently commited (RSpec 2.0.0.beta.18) was the ability to pass a block to "it_should_behave_like", making the relation clearer; eg: describe MyStruct do it_should_behave_like 'a Struct' do let(:struct) { MyStruct.new } end end I did ask about parametrizing that explicitly via metadata, but David feels that the block based approach is better; see the full thread here: http://github.com/rspec/rspec-core/issues/71 Wincent From ashley.moran at patchspace.co.uk Fri Jul 23 05:38:49 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Fri, 23 Jul 2010 10:38:49 +0100 Subject: [rspec-users] Parameterised shared examples / metadata in examples (RSpec 2) In-Reply-To: <930905AA-123D-46E1-A7F5-74C6AA1618B3@wincent.com> References: <7854C363-C02F-45DA-8296-32051F12E16B@patchspace.co.uk> <930905AA-123D-46E1-A7F5-74C6AA1618B3@wincent.com> Message-ID: <2C8ED2DA-2879-4586-862F-A0C65EEE6708@patchspace.co.uk> On Jul 23, 2010, at 8:57 am, Wincent Colaiuta wrote: > Recently commited (RSpec 2.0.0.beta.18) was the ability to pass a block to "it_should_behave_like", making the relation clearer; eg: > > describe MyStruct do > it_should_behave_like 'a Struct' do > let(:struct) { MyStruct.new } > end > end > > I did ask about parametrizing that explicitly via metadata, but David feels that the block based approach is better; see the full thread here: > > http://github.com/rspec/rspec-core/issues/71 And I only just tweeted about that ticket too! I didn't review it all though, I just saw the aliasing (which I currently do by hand). That's in beta 18 then? Pretty sure I just got that when I updated this morning. Will play around with it later... Cheers Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From noreply at mail.goodreads.com Fri Jul 23 11:47:17 2010 From: noreply at mail.goodreads.com (Varchar) Date: Fri, 23 Jul 2010 08:47:17 -0700 Subject: [rspec-users] Check out my shelves Message-ID: <4c49b985a195b_5d915d0329cf9b057681552@legolas.colo.tmail> Hi rspec, Check out the books I added on Goodreads. http://www.goodreads.com/friend/i?n=rspec users&e=rspec-users at rubyforge.org&i=LTM2MDMwNTExMjM6MzY1 - Varchar (charlesmbowman at gmail.com) Goodreads is a community for book lovers. It's a great way to get book recommendations from your friends and others. You can keep a list of books to read, join book clubs, and even take the never-ending book trivia quiz. _____________________________ To opt-out of future invites to Goodreads please follow this link: http://www.goodreads.com/user/block_email?inviter_id=4047707 This email was sent by request to rspec-users at rubyforge.org. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Fri Jul 23 12:11:52 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 23 Jul 2010 11:11:52 -0500 Subject: [rspec-users] Check out my shelves In-Reply-To: <4c49b985a195b_5d915d0329cf9b057681552@legolas.colo.tmail> References: <4c49b985a195b_5d915d0329cf9b057681552@legolas.colo.tmail> Message-ID: On Fri, Jul 23, 2010 at 10:47 AM, Varchar wrote: > Hi rspec, > > Check out the books I added on Goodreads. All, please do what you can to keep this sort of spam from coming to this list. That means when you sign up for services and have them email all your contacts, you need to make sure this list gets excluded. Cheers, David From patgannon at gmail.com Fri Jul 23 20:29:24 2010 From: patgannon at gmail.com (Patrick Gannon) Date: Fri, 23 Jul 2010 17:29:24 -0700 Subject: [rspec-users] [Rails] Stubbed static methods are bleeding over into other specs and making them fail In-Reply-To: <29F1F5F4-9E70-4F0E-8D2E-8E04E510D957@gmail.com> References: <2F30C790-F219-4DD4-8932-8238E66C752D@gmail.com> <29F1F5F4-9E70-4F0E-8D2E-8E04E510D957@gmail.com> Message-ID: > > I just got a chance to try this, and ran into more problems. Prior to > trying this, we were running RSpec2 beta 13. When I changed our Gemfile to > depend on 'edge' RSpec et al (as you suggested above), I get a very strange > error when I run rake (after doing a 'bundle install'). The same error > occurs after I tell it specifically to use beta 16 (rather than 'edge'). It > seems to somehow not be able to find the bundler gem when it runs the main > bundler script from within rake: > > C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:779:in > `report_activate_error': Could not find RubyGem bundler (>= 0) > (Gem::LoadError) > from C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:214:in > `activate' > from C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:1082:in `gem' > from C:/Ruby187/bin/bundle:18 > rake aborted! > bundle exec C:/Ruby187/bin/ruby.exe -Ilib -Ispec > "./spec/controllers/discrepancies_controller_spec.rb" *(...spec names > omitted..)* failed > > When I downgrade back to beta 13, everything works again. I can't seem to > figure out why it wouldn't be able to find the bundler gem (since obviously > bundler is installed), so I cannot say whether or not your fix for the > stubbing issue solved my problem. The stack trace (resulting from running > rake with "--trace") and my current list of installed gems (via "bundle > list") is here: http://gist.github.com/470278 (sorry for the line breaks) > > > bundler-1.0.0.beta.4 should fix this. Please give it a shot. > Ok, I upgraded to bundler 1.0 beta 9 and configured Gemfile to use edge RSpec et al (as recommended above). After doing a 'bundle install', our tests failed (without trying to re-enable any of the mocking functionality originally mentioned). It appears that now RSpec is trying to reference ActiveRecord, even though we're not using ActiveRecord. (We specifically require each of the railties other than ActiveRecord in application.rb, rather than requiring rails/all.) The error that rake produces is: Don't know how to build task 'db:test:prepare'. I then went ahead and defined an empty rake task called db:test:prepare, and then got another error relating to ActiveRecord: uninitialized constant RSpec::Rails::FixtureSupport::ActiveRecord (NameError). Stack trace is here: https://gist.github.com/acbaf0a384b301013140 (sorry for the formatting - copied/pasted from a DOS window). I then tried to use RSpec 2.0 beta.16 (rather than edge) and it skipped straight to the aforementioned error (even when db:test:prepare wasn't defined, it didn't complain about that). Thanks, Pat -------------- next part -------------- An HTML attachment was scrubbed... URL: From lille.penguini at gmail.com Fri Jul 23 19:46:07 2010 From: lille.penguini at gmail.com (Lille) Date: Fri, 23 Jul 2010 16:46:07 -0700 (PDT) Subject: [rspec-users] newbie: how to preserve NoMethodError under stubbing? Message-ID: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> Hi, I've been browsing the RSpec book and the RDoc, but I can't see how to ensure the following: Stub an instance with a method it doesn't have and raise NoMethodError (or something like it.) I want to do this because I don't want to use incorrect names for my dependency methods... Thanks, Lille From dchelimsky at gmail.com Sat Jul 24 02:26:27 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 24 Jul 2010 01:26:27 -0500 Subject: [rspec-users] newbie: how to preserve NoMethodError under stubbing? In-Reply-To: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> References: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> Message-ID: On Fri, Jul 23, 2010 at 6:46 PM, Lille wrote: > Hi, > > I've been browsing the RSpec book and the RDoc, but I can't see how to > ensure the following: > > Stub an instance with a method it doesn't have and raise NoMethodError > (or something like it.) RSpec doesn't support anything like that. I'm not sure if any of the Ruby frameworks do, though I've been involved with conversations about this sort of thing before. I wouldn't want behaviour like this myself unless it could be invoked explicitly with a command line argument, but was otherwise off. In other words, you could do something like: rspec spec --audit-stubbed-methods And then that would generate some sort of report. Feel free to submit a feature request to http://github.com/rspec/rspec-mocks if you're interested in pursuing such. Cheers, David > > I want to do this because I don't want to use incorrect names for my > dependency methods... > > Thanks, > > Lille > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From dchelimsky at gmail.com Sat Jul 24 02:36:28 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 24 Jul 2010 01:36:28 -0500 Subject: [rspec-users] [Rails] Stubbed static methods are bleeding over into other specs and making them fail In-Reply-To: References: <2F30C790-F219-4DD4-8932-8238E66C752D@gmail.com> <29F1F5F4-9E70-4F0E-8D2E-8E04E510D957@gmail.com> Message-ID: On Fri, Jul 23, 2010 at 7:29 PM, Patrick Gannon wrote: >> I just got a chance to try this, and ran into more problems. ?Prior to >> trying this, we were running RSpec2 beta 13. ?When I changed our Gemfile to >> depend on 'edge' RSpec et al (as you suggested above), I get a very strange >> error when I run rake (after doing a 'bundle install'). ?The same error >> occurs after I?tell it specifically to use beta 16 (rather than 'edge'). ?It >> seems to somehow not be able to find the bundler gem when it runs the main >> bundler script from within rake: >> C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:779:in >> `report_activate_error': Could not find RubyGem bundler (>= 0) >> (Gem::LoadError) >> ?? ? ? ?from C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:214:in >> `activate' >> ?? ? ? ?from C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems.rb:1082:in `gem' >> ?? ? ? ?from C:/Ruby187/bin/bundle:18 >> rake aborted! >> bundle exec ?C:/Ruby187/bin/ruby.exe ?-Ilib -Ispec >> "./spec/controllers/discrepancies_controller_spec.rb" (...spec names >> omitted..)?failed >> When I downgrade back to beta 13, everything works again. ?I can't seem to >> figure out why it wouldn't be able to find the bundler gem (since obviously >> bundler is installed), so I cannot say whether or not your fix for the >> stubbing issue solved my problem. ?The stack trace (resulting from running >> rake with "--trace") and my current list of installed gems (via "bundle >> list") is here:?http://gist.github.com/470278?(sorry for the line breaks) >> >> bundler-1.0.0.beta.4 should fix this. Please give it a shot. > > Ok, I upgraded to bundler 1.0 beta 9 and configured Gemfile to use edge > RSpec et al (as recommended above). ?After doing a 'bundle install', our > tests failed (without trying to re-enable any of the mocking functionality > originally mentioned). ?It appears that now RSpec is trying to reference > ActiveRecord, even though we're not using ActiveRecord. ?(We specifically > require each of the railties other than ActiveRecord in application.rb, > rather than requiring rails/all.) ?The error that rake produces is:?Don't > know how to build task 'db:test:prepare'. ?I then went ahead and defined an > empty rake task called db:test:prepare, and then got another error relating > to ActiveRecord:?uninitialized constant > RSpec::Rails::FixtureSupport::ActiveRecord (NameError). ?Stack trace is > here:?https://gist.github.com/acbaf0a384b301013140?(sorry for the formatting > - copied/pasted from a DOS window). ?I then tried to use RSpec 2.0 beta.16 > (rather than edge) and it skipped straight to the aforementioned error (even > when db:test:prepare wasn't defined, it didn't complain about that). > Thanks, > Pat OK - I believe I've fixed the ActiveRecord problem. Please try "bundle install" again (make sure you get rspec-rails >= 83f2a44bfd31e7133248bba67bfe3ad89dc59b27. HTH, David From matt at mattwynne.net Sat Jul 24 04:55:16 2010 From: matt at mattwynne.net (Matt Wynne) Date: Sat, 24 Jul 2010 10:55:16 +0200 Subject: [rspec-users] newbie: how to preserve NoMethodError under stubbing? In-Reply-To: References: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> Message-ID: <1279961716.18377.1386501709@webmail.messagingengine.com> Lille, On Sat, 24 Jul 2010 01:26 -0500, "David Chelimsky" wrote: > On Fri, Jul 23, 2010 at 6:46 PM, Lille wrote: > > Hi, > > > > I've been browsing the RSpec book and the RDoc, but I can't see how to > > ensure the following: > > > > Stub an instance with a method it doesn't have and raise NoMethodError > > (or something like it.) > > RSpec doesn't support anything like that. I'm not sure if any of the > Ruby frameworks do, though I've been involved with conversations about > this sort of thing before. > > I wouldn't want behaviour like this myself unless it could be invoked > explicitly with a command line argument, but was otherwise off. In > other words, you could do something like: > > rspec spec --audit-stubbed-methods > > And then that would generate some sort of report. > > Feel free to submit a feature request to > http://github.com/rspec/rspec-mocks if you're interested in pursuing > such. > > Cheers, > David Most people ask for this kind of feature from their unit tests because they're not combining mocking unit tests with end-to-end acceptance tests. Are you using both? > > > > > > I want to do this because I don't want to use incorrect names for my > > dependency methods... > > > > Thanks, > > > > Lille > > _______________________________________________ > > 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 > From win at wincent.com Sat Jul 24 05:35:56 2010 From: win at wincent.com (Wincent Colaiuta) Date: Sat, 24 Jul 2010 11:35:56 +0200 Subject: [rspec-users] newbie: how to preserve NoMethodError under stubbing? In-Reply-To: References: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> Message-ID: El 24/07/2010, a las 08:26, David Chelimsky escribi?: > On Fri, Jul 23, 2010 at 6:46 PM, Lille wrote: >> Hi, >> >> I've been browsing the RSpec book and the RDoc, but I can't see how to >> ensure the following: >> >> Stub an instance with a method it doesn't have and raise NoMethodError >> (or something like it.) > > RSpec doesn't support anything like that. I'm not sure if any of the > Ruby frameworks do, though I've been involved with conversations about > this sort of thing before. I'm not sure if I understand the request, but with RR you can do this: >> require 'rr' => true >> extend RR::Adapters::RRMethods => main >> foo = Object.new => # >> stub(foo).bar { raise NoMethodError } => # >> foo.bar NoMethodError: NoMethodError Although like I said, not sure if I understood Lille's request. Cheers, Wincent From dchelimsky at gmail.com Sat Jul 24 07:15:59 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 24 Jul 2010 06:15:59 -0500 Subject: [rspec-users] newbie: how to preserve NoMethodError under stubbing? In-Reply-To: References: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> Message-ID: <24D3F3D2-7ADC-44B1-97F8-F1C619B8297E@gmail.com> On Jul 24, 2010, at 4:35 AM, Wincent Colaiuta wrote: > El 24/07/2010, a las 08:26, David Chelimsky escribi?: > >> On Fri, Jul 23, 2010 at 6:46 PM, Lille wrote: >>> Hi, >>> >>> I've been browsing the RSpec book and the RDoc, but I can't see how to >>> ensure the following: >>> >>> Stub an instance with a method it doesn't have and raise NoMethodError >>> (or something like it.) >> >> RSpec doesn't support anything like that. I'm not sure if any of the >> Ruby frameworks do, though I've been involved with conversations about >> this sort of thing before. > > I'm not sure if I understand the request, but with RR you can do this: > >>> require 'rr' > => true >>> extend RR::Adapters::RRMethods > => main >>> foo = Object.new > => # >>> stub(foo).bar { raise NoMethodError } > => # >>> foo.bar > NoMethodError: NoMethodError > > Although like I said, not sure if I understood Lille's request. I read the request as this: class Foo def bar; end end f = Foo.new f.stub(:barr) #=> Error: "The Foo class does not have a 'barr' method. Perhaps you meant to stub 'bar'" For me this would have very limited utility because 1/2 the time I'm deliberately stubbing methods that don't even exist yet on doubles doubling for objects that don't even exist yet, which is why I wouldn't want it to be something that happens implicitly by default. Here's another thread on the same matter from a little over a year ago: http://groups.google.com/group/rspec/browse_thread/thread/cf0b3eae192b9d8c/f5b77b008de628c7?lnk=gst&q=mock+audit#f5b77b008de628c7 Cheers, David > > Cheers, > Wincent From lille.penguini at gmail.com Sat Jul 24 09:34:01 2010 From: lille.penguini at gmail.com (Lille) Date: Sat, 24 Jul 2010 06:34:01 -0700 (PDT) Subject: [rspec-users] newbie: how to preserve NoMethodError under stubbing? In-Reply-To: <24D3F3D2-7ADC-44B1-97F8-F1C619B8297E@gmail.com> References: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> <24D3F3D2-7ADC-44B1-97F8-F1C619B8297E@gmail.com> Message-ID: <3ea7afb4-cb33-4d78-8319-649d8ad148d6@t10g2000yqg.googlegroups.com> David, Yes, your reading of the request is what I originally meant. I appreciate the points made by others in this thread and the thread David has referred to. As I continue to learn RSpec I will undoubtedly avail myself of the approaches recommended above or in the linked thread, but I think an argument to stub() per the following could be useful: f.stub(:barr, :throw_no_such_method_error=>true) #=> Error: "The Foo class does not have a 'barr' method. Perhaps you meant to stub 'bar'" Thanks, Lille On Jul 24, 7:15?am, David Chelimsky wrote: > On Jul 24, 2010, at 4:35 AM, Wincent Colaiuta wrote: > > > > > > > El 24/07/2010, a las 08:26, David Chelimsky escribi?: > > >> On Fri, Jul 23, 2010 at 6:46 PM, Lille wrote: > >>> Hi, > > >>> I've been browsing the RSpec book and the RDoc, but I can't see how to > >>> ensure the following: > > >>> Stub an instance with a method it doesn't have and raise NoMethodError > >>> (or something like it.) > > >> RSpec doesn't support anything like that. I'm not sure if any of the > >> Ruby frameworks do, though I've been involved with conversations about > >> this sort of thing before. > > > I'm not sure if I understand the request, but with RR you can do this: > > >>> require 'rr' > > => true > >>> extend RR::Adapters::RRMethods > > => main > >>> foo = Object.new > > => # > >>> stub(foo).bar { raise NoMethodError } > > => # > >>> foo.bar > > NoMethodError: NoMethodError > > > Although like I said, not sure if I understood Lille's request. > > I read the request as this: > > class Foo > ? def bar; end > end > > f = Foo.new > f.stub(:barr) > #=> Error: "The Foo class does not have a 'barr' method. Perhaps you meant to stub 'bar'" > > For me this would have very limited utility because 1/2 the time I'm deliberately stubbing methods that don't even exist yet on doubles doubling for objects that don't even exist yet, which is why I wouldn't want it to be something that happens implicitly by default. > > Here's another thread on the same matter from a little over a year ago: > > http://groups.google.com/group/rspec/browse_thread/thread/cf0b3eae192... > > Cheers, > David > > > > > Cheers, > > Wincent > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From win at wincent.com Sat Jul 24 09:52:40 2010 From: win at wincent.com (Wincent Colaiuta) Date: Sat, 24 Jul 2010 15:52:40 +0200 Subject: [rspec-users] newbie: how to preserve NoMethodError under stubbing? In-Reply-To: <3ea7afb4-cb33-4d78-8319-649d8ad148d6@t10g2000yqg.googlegroups.com> References: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> <24D3F3D2-7ADC-44B1-97F8-F1C619B8297E@gmail.com> <3ea7afb4-cb33-4d78-8319-649d8ad148d6@t10g2000yqg.googlegroups.com> Message-ID: <1C0CD604-51E7-47EA-AB3C-F58A2DE90A78@wincent.com> El 24/07/2010, a las 15:34, Lille escribi?: > David, > > Yes, your reading of the request is what I originally meant. > > I appreciate the points made by others in this thread and the thread > David has referred to. > > As I continue to learn RSpec I will undoubtedly avail myself of the > approaches recommended above or in the linked thread, but I think an > argument to stub() per the following could be useful: > > f.stub(:barr, :throw_no_such_method_error=>true) > #=> Error: "The Foo class does not have a 'barr' method. Perhaps you > meant to stub 'bar'" How about this: f.stub.existing(:bar) That's probably RR influencing me there, which employs things like "stub.proxy" and so on. So maybe not such a good idea for rspec-mocks. Cheers, Wincent From chatgri at gmail.com Sat Jul 24 10:33:37 2010 From: chatgri at gmail.com (chatgris) Date: Sat, 24 Jul 2010 07:33:37 -0700 (PDT) Subject: [rspec-users] Controller stub and helper spec with lastest beta Message-ID: Hello, I have two issues with beta 2.0.0.beta.18. First, here's the gems : gem "rails", "3.0.0.beta4" gem "mongoid", "2.0.0.beta10" group :test do gem "rspec-rails", "2.0.0.beta.18" gem "factory_girl_rails", "1.0" end My spec_helper : http://github.com/chatgris/blabbr/blob/spec/spec/spec_helper.rb First issue is related to stubbing the current_user method in controller. describe 'current_user == added_by' do before :all do @current_user = Factory.create(:user) @smiley = Factory.create(:smiley) end before :each do controller.stub!(:logged_in?).and_return(true) controller.stub!(:current_user).and_return(@current_user) end it 'should be able to see index' do get :index response.should be_success end end current_user is defined in application_controller.rb That code have this result : SmiliesController current_user == added_by should be able to see index Failure/Error: controller.stub!(:logged_in?).and_return(true) undefined method `stub!' for # # ./spec/controllers/smilies_controller_spec.rb:36 The other issue is related to helpers specs. Considers this code : require 'spec_helper' describe LinkHelper do before :all do @user = Factory.create(:creator) @topic = Factory.build(:topic) end it "displays a 80px width gravatar link to the user page" do helper.link_to_avatar(@user).should == "\"4f64c9f81bb0d4ee969aaf7b4a5a6f40\"" end end That gives this error : LinkHelper displays a 80px width gravatar link to the user page Failure/Error: Unable to find matching line from backtrace undefined local variable or method `example' for # # /home/chatgris/.bundle/ruby/1.8/bundler/gems/rspec- rails-863ffee12bd6030ece577b07c39297c14aacad85-master/lib/rspec/rails/ example/helper_example_group.rb:54:in `_controller_path' # /home/chatgris/.bundle/ruby/1.8/bundler/gems/rspec- rails-863ffee12bd6030ece577b07c39297c14aacad85-master/lib/rspec/rails/ example/helper_example_group.rb:61 Thanks for your help. From dchelimsky at gmail.com Sat Jul 24 11:24:57 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sat, 24 Jul 2010 10:24:57 -0500 Subject: [rspec-users] Controller stub and helper spec with lastest beta In-Reply-To: References: Message-ID: <413F2355-7251-4CE8-B498-95EEED447237@gmail.com> On Jul 24, 2010, at 9:33 AM, chatgris wrote: > Hello, > > I have two issues with beta 2.0.0.beta.18. First, here's the gems : > > gem "rails", "3.0.0.beta4" > gem "mongoid", "2.0.0.beta10" > > group :test do > gem "rspec-rails", "2.0.0.beta.18" > gem "factory_girl_rails", "1.0" > end > > My spec_helper : http://github.com/chatgris/blabbr/blob/spec/spec/spec_helper.rb You've got some unnecessary stuff in spec_helper.rb. Try this: 1. Include rspec-rails in the :development group so you can see its rake tasks and generators [1] 2. Move all the configuration (except mock_with :rspec) from spec_helper to another file in spec/support/. 2. Regenerate spec_helper by running "script/rails generate rspec:install" [1] http://blog.davidchelimsky.net/2010/07/11/rspec-rails-2-generators-and-rake-tasks-part-ii/ > First issue is related to stubbing the current_user method in > controller. > > describe 'current_user == added_by' do > > before :all do > @current_user = Factory.create(:user) > @smiley = Factory.create(:smiley) > end This is probably not related to these issues, but it's generally better to create DB-backed objects (i.e. using Factory.create) in before(:each) blocks so they get the benefit of Rails' transaction management. > before :each do > controller.stub!(:logged_in?).and_return(true) > controller.stub!(:current_user).and_return(@current_user) > end > > it 'should be able to see index' do > get :index > response.should be_success > end > end > > current_user is defined in application_controller.rb > > That code have this result : > > SmiliesController current_user == added_by should be able to see index > Failure/Error: controller.stub!(:logged_in?).and_return(true) > undefined method `stub!' for # > # ./spec/controllers/smilies_controller_spec.rb:36 This suggests that something is getting in the way of loading rspec-mocks correctly. Please follow directions above and let me know if that solves it. > The other issue is related to helpers specs. Considers this code : > > require 'spec_helper' > > describe LinkHelper do > before :all do > @user = Factory.create(:creator) > @topic = Factory.build(:topic) > end > > it "displays a 80px width gravatar link to the user page" do > helper.link_to_avatar(@user).should == " \">\"4f64c9f81bb0d4ee969aaf7b4a5a6f40\" www.gravatar.com/avatar/4f64c9f81bb0d4ee969aaf7b4a5a6f40.jpg?size=80\" > />" > end > > end > > That gives this error : > > LinkHelper displays a 80px width gravatar link to the user page > Failure/Error: Unable to find matching line from backtrace > undefined local variable or method `example' for > # > # /home/chatgris/.bundle/ruby/1.8/bundler/gems/rspec- > rails-863ffee12bd6030ece577b07c39297c14aacad85-master/lib/rspec/rails/ > example/helper_example_group.rb:54:in `_controller_path' I think this is the source of the problem. It looks like bundler is loading some version of rspec-rails other than the "2.0.0.beta.18" that is specified in the Gemfile. What version of bundler are you using? > # /home/chatgris/.bundle/ruby/1.8/bundler/gems/rspec- > rails-863ffee12bd6030ece577b07c39297c14aacad85-master/lib/rspec/rails/ > example/helper_example_group.rb:61 > > > Thanks for your help. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From win at wincent.com Sat Jul 24 11:12:11 2010 From: win at wincent.com (Wincent Colaiuta) Date: Sat, 24 Jul 2010 17:12:11 +0200 Subject: [rspec-users] Controller stub and helper spec with lastest beta In-Reply-To: References: Message-ID: <5337332D-74D8-4610-BC73-2086B9758FEA@wincent.com> El 24/07/2010, a las 16:33, chatgris escribi?: > I have two issues with beta 2.0.0.beta.18. First, here's the gems : > > gem "rails", "3.0.0.beta4" > gem "mongoid", "2.0.0.beta10" > > group :test do > gem "rspec-rails", "2.0.0.beta.18" > gem "factory_girl_rails", "1.0" > end [snip] > That gives this error : > > LinkHelper displays a 80px width gravatar link to the user page > Failure/Error: Unable to find matching line from backtrace > undefined local variable or method `example' for > # > # /home/chatgris/.bundle/ruby/1.8/bundler/gems/rspec- > rails-863ffee12bd6030ece577b07c39297c14aacad85-master/lib/rspec/rails/ > example/helper_example_group.rb:54:in `_controller_path' > # /home/chatgris/.bundle/ruby/1.8/bundler/gems/rspec- > rails-863ffee12bd6030ece577b07c39297c14aacad85-master/lib/rspec/rails/ > example/helper_example_group.rb:61 Strange that you've asked for 2.0.0.beta.18 and Bundler is giving you a Git version. What version of Bundler are you using? Given that "running_example" was renamed to "example" in commit f3de9311, I wonder if you have some kind of Bundler issue which means you're running a newer version of rspec-rails against an older version of rspec-core. Cheers, Wincent From ashley.moran at patchspace.co.uk Sat Jul 24 13:08:19 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sat, 24 Jul 2010 18:08:19 +0100 Subject: [rspec-users] newbie: how to preserve NoMethodError under stubbing? In-Reply-To: <1C0CD604-51E7-47EA-AB3C-F58A2DE90A78@wincent.com> References: <4bfa2d13-882f-473a-ac35-c8363b68800d@t10g2000yqg.googlegroups.com> <24D3F3D2-7ADC-44B1-97F8-F1C619B8297E@gmail.com> <3ea7afb4-cb33-4d78-8319-649d8ad148d6@t10g2000yqg.googlegroups.com> <1C0CD604-51E7-47EA-AB3C-F58A2DE90A78@wincent.com> Message-ID: <45114428-E684-4866-8C46-440F32279D61@patchspace.co.uk> On 24 Jul 2010, at 2:52 PM, Wincent Colaiuta wrote: > How about this: > > f.stub.existing(:bar) > > That's probably RR influencing me there, which employs things like "stub.proxy" and so on. So maybe not such a good idea for rspec-mocks. Another option might be to deprecate #stub! as an alias for #stub and then bring it back as an equivalent to `stub.existing` above. Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From costa at mouldwarp.com Sat Jul 24 22:10:44 2010 From: costa at mouldwarp.com (Costa Shapiro) Date: Sat, 24 Jul 2010 22:10:44 -0400 Subject: [rspec-users] How it would be tested? In-Reply-To: References: <85af84d2-96db-4978-92ea-2519583569e0@b35g2000yqi.googlegroups.com> Message-ID: Alright, as far as I know, the most common approach is to make up some data for each controller spec, and one of the techniques for doing this is fixtures (e.g. found in rails) -- another is the mocks, of course. Fixtures aren't exactly the hottest offer today, but to me, they are probably the easiest choice for those messages of yours. So, I suppose you may want to type in some message data in the corresponding fixture file. (see http://ar.rubyonrails.org/classes/Fixtures.html etc). If you insist on mocking the messages, that would primarily go into before :all block. Then, in the blocks like 'it "should see all public messages"' you make requests with the correctly mocked user and check the returned messages versus the test data (you know which messages are supposed to return). Good luck, Costa. On 21 July 2010 22:41, tests learner wrote: > Costa Shapiro, > > Thank you for paying atention. > > But How i would write if i don't know nothing about the code ? > > My problem is: > I have a messages listing section that will differ according of type > of user and according with message permission. > I have messages that are public and private. > Anyone can see public messages. > The private messages only can be accessed by who participate on them > and users that have Owner role on system. > > How it would be tested ? > Since my listing have to list: > if user not owner: > - public messages + messages that the user can view because he > participate on them > if user is owner: > - all messages. > > So i think the behavior that i have to spec is: > > context "guests" do (for ex.) > ? before(:all) do > ? ? #mock a guest here > ? end > ? ?it "should see all public messages" > ? ?it "should see all messages that participate" > end > > context "owners" do > ? before(:all) do > ? ? #mock a owner here > ? end > ? it "should see all messages" > end > > > Right? > I'll be grateful, if you could give any hint about the spec code. > > > Greets, > > > > On 21 jul, 17:24, Costa Shapiro wrote: >> Dear Mr. Learner, >> >> Please note that while very similar in functionality, specs' philosophy >> differs from tests' (especially from non-TDD ones). >> That is, you write spec first, see it fail, and write some code to make it >> pass. >> If you happen to write any implementation code first, you should disregard >> it while writing a spec. >> You may find BDD reading in abundance on the internets. >> >> To get a more substantial reply, I think you might want to describe what you >> want your code to do in plain English, and the community will hopefully help >> you to express that in rspec. >> >> Cheers, >> Costa. >> >> On 12 July 2010 13:35, tests learner wrote: >> >> > Hello all. >> >> > I'm working with rails and came to a situation that i cannot imagine >> > how to test this. >> >> > Given i have an index action that retrieves me a collection of >> > objects. >> > But some of them have especific permissions. >> >> > My index action act like this: >> > - retrieve public objects. >> > - retrieve permission 1 objects. >> > - retrieve permission 2 objects. >> >> > So i have to write 3 tests. >> >> > it "should retrieve public objects" >> >> > context "permission 1" >> > ?it " should retrieve permission 1 objects" >> > context "permission 2" >> > ?it "should retrieve permission 2 objects" >> >> > Until here no problems because only conditional tests and method >> > calls. >> >> > But how i would test the "Index.retrieve_objects_from_permission1" ? >> >> > supose i have >> >> > class ?Index < ActiveRecord::Base >> > ? has_many :permissions >> > ? def self.retrieve_objects_from_permission1 >> > ? ? ? Index.all(:conditions => "permissions.id = 1", :include >> > => :permissions) >> > ? end >> >> > ? ?def has_permission1 >> > ? ? ? !self.permissions.find_by_id(1).nil? >> > ? ?end >> > end >> >> > My Index.retrieve_objects_from_permission1 would be: >> >> > it "should retrieve objects that have permission 1" do >> > ? @collection = Index.retrieve_objects_from_permission1 >> > ? @collection.each do |c| >> > ? ? ? c.has_permission1.should == true >> > ? ?end >> > end >> >> > Is it right? ( I didn't see it before on other's code, so i don't >> > think it's right.) >> >> > Sorry for my poor english. i hope I have been clear enough. >> >> > Thank you :) >> > _______________________________________________ >> > rspec-users mailing list >> > rspec-us... at rubyforge.org >> >http://rubyforge.org/mailman/listinfo/rspec-users >> >> >> >> _______________________________________________ >> rspec-users mailing list >> rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users > From costa at mouldwarp.com Sat Jul 24 22:39:55 2010 From: costa at mouldwarp.com (Costa Shapiro) Date: Sat, 24 Jul 2010 22:39:55 -0400 Subject: [rspec-users] rspec-orm and _not_ mocking models In-Reply-To: References: Message-ID: I'm sorry, I'd like to clarify my statement about the model, view and controller (spec) separation. >From my perspective, model is an abstract definition which is a spec for itself; view interacts with controller under the model contract, and all the "model" code is actually low-level controller code which makes the high-level code work. Alternatively, it can be trivially said that the database state is equivalent to a sequence of controller requests. Hence the inclination to see the least model-related code in specs. Thanks, Costa. On 21 July 2010 17:28, Costa Shapiro wrote: > Hello, > > (Surprisingly?) I find mocking AR (DM less so) in specs extremely tedious > _and_ intrusive. > > Having said this, I find the approach of top-down VCM speccing very > legitimate (cucumber for V, rspec for C, and probably unit tests for M). > That is, a model is an inherent though separate part of the controller and > trying to spec just the controller lacks efficiency (pragmatism) and leads > to frustration. > > Therefore, I've starting working on http://github.com/costa/rspec-orm > (everything is of concept-quality there, including the name). It's already > "working for me". > I think the README there pretty much cuts it, so I'd just welcome the > comments here. > Note that ? I'm sorry ? the code is not only unpackaged, but it is in a > separate http://github.com/costa/dev/tree/master/ruby/ in part (for a > reason). > > Again, *any* feedback is appreciated. > > Cheers, > Costa. > From ashley.moran at patchspace.co.uk Sun Jul 25 04:40:38 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sun, 25 Jul 2010 09:40:38 +0100 Subject: [rspec-users] rspec-orm and _not_ mocking models In-Reply-To: References: Message-ID: <6995C0C4-58C0-4CAA-A50A-173A04B6BAC8@patchspace.co.uk> On 21 Jul 2010, at 10:28 PM, Costa Shapiro wrote: > (Surprisingly?) I find mocking AR (DM less so) in specs extremely tedious _and_ intrusive. Yeah, I know what you mean, I just don't do it any more. I find the pain isn't worth it on the stuff I do. > I think the README there pretty much cuts it, so I'd just welcome the comments here. One very minor point, you're got a comment to maybe empty the database afterwards. It's more useful to empty it before, as then you've still got the data in the database after a failing example. Also, if you haven't seen it, Ben Mabey wrote a tool for this[1]. Oh and I wrote one for rebuilding your database if migrations change[2], plug plug :D Ash [1] http://github.com/bmabey/database_cleaner [2] http://rubygems.org/gems/database_resetter -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From chatgri at gmail.com Sun Jul 25 10:19:04 2010 From: chatgri at gmail.com (chatgris) Date: Sun, 25 Jul 2010 07:19:04 -0700 (PDT) Subject: [rspec-users] Controller stub and helper spec with lastest beta In-Reply-To: <413F2355-7251-4CE8-B498-95EEED447237@gmail.com> References: <413F2355-7251-4CE8-B498-95EEED447237@gmail.com> Message-ID: <76a5d990-ddca-4356-8e70-7c05d7768728@j8g2000yqd.googlegroups.com> Thank you for those advices David. It wasn't related to bundler. I did a big clean up in spec_helper.rb and in my gem list. I still had rspec.rake in lib/tasks/ . Now, everything works as expected via autotest or rake:spec. Thanks. Julien On 24 juil, 17:24, David Chelimsky wrote: > On Jul 24, 2010, at 9:33 AM, chatgris wrote: > > > Hello, > > > I have two issues with beta 2.0.0.beta.18. First, here's the gems : > > > gem "rails", "3.0.0.beta4" > > gem "mongoid", "2.0.0.beta10" > > > group :test do > > ?gem "rspec-rails", "2.0.0.beta.18" > > ?gem "factory_girl_rails", "1.0" > > end > > > My spec_helper :http://github.com/chatgris/blabbr/blob/spec/spec/spec_helper.rb > > You've got some unnecessary stuff in spec_helper.rb. Try this: > > 1. Include rspec-rails in the :development group so you can see its rake tasks and generators [1] > 2. Move all the configuration (except mock_with :rspec) from spec_helper to another file in spec/support/. > 2. Regenerate spec_helper by running "script/rails generate rspec:install" > > [1]http://blog.davidchelimsky.net/2010/07/11/rspec-rails-2-generators-an... > > > First issue is related to stubbing the current_user method in > > controller. > > > describe 'current_user == added_by' do > > > ? ?before :all do > > ? ? ?@current_user = Factory.create(:user) > > ? ? ?@smiley = Factory.create(:smiley) > > ? ?end > > This is probably not related to these issues, but it's generally better to create DB-backed objects (i.e. using Factory.create) in before(:each) blocks so they get the benefit of Rails' transaction management. > > > > > ? ?before :each do > > ? ? ?controller.stub!(:logged_in?).and_return(true) > > ? ? ?controller.stub!(:current_user).and_return(@current_user) > > ? ?end > > > ? ?it 'should be able to see index' do > > ? ? ?get :index > > ? ? ?response.should be_success > > ? ?end > > end > > > current_user is defined in application_controller.rb > > > That code have this result : > > > SmiliesController current_user == added_by should be able to see index > > ? ?Failure/Error: controller.stub!(:logged_in?).and_return(true) > > ? ?undefined method `stub!' for # > > ? ?# ./spec/controllers/smilies_controller_spec.rb:36 > > This suggests that something is getting in the way of loading rspec-mocks correctly. Please follow directions above and let me know if that solves it. > > > > > The other issue is related to helpers specs. Considers this code : > > > require 'spec_helper' > > > describe LinkHelper do > > ?before :all do > > ? ?@user = Factory.create(:creator) > > ? ?@topic = Factory.build(:topic) > > ?end > > > ?it "displays a 80px width gravatar link to the user page" do > > ? ?helper.link_to_avatar(@user).should == " > \">\"4f64c9f81bb0d4ee969aaf7b4a5a6f40\" >www.gravatar.com/avatar/4f64c9f81bb0d4ee969aaf7b4a5a6f40.jpg?size=80\" > > />" > > ?end > > > end > > > That gives this error : > > > LinkHelper displays a 80px width gravatar link to the user page > > ? ?Failure/Error: Unable to find matching line from backtrace > > ? ?undefined local variable or method `example' for > > # > > ? ?# /home/chatgris/.bundle/ruby/1.8/bundler/gems/rspec- > > rails-863ffee12bd6030ece577b07c39297c14aacad85-master/lib/rspec/rails/ > > example/helper_example_group.rb:54:in `_controller_path' > > I think this is the source of the problem. It looks like bundler is loading some version of rspec-rails other than the "2.0.0.beta.18" that is specified in the Gemfile. > > What version of bundler are you using? > > > ? ?# /home/chatgris/.bundle/ruby/1.8/bundler/gems/rspec- > > rails-863ffee12bd6030ece577b07c39297c14aacad85-master/lib/rspec/rails/ > > example/helper_example_group.rb:61 > > > Thanks for your help. > > _______________________________________________ > > rspec-users mailing list > > rspec-us... at rubyforge.org > >http://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Sun Jul 25 14:29:24 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Sun, 25 Jul 2010 13:29:24 -0500 Subject: [rspec-users] what is the value of the distinction between exceptions and failures? Message-ID: There is a feature request to make a distinction between exceptions and logical failures in RSpec's output. If this topic interests you, please take a look at http://github.com/rspec/rspec-core/issues/#issue/93 and add your thoughts to the conversation there. Thx, David From elliot.winkler at gmail.com Sun Jul 25 15:47:50 2010 From: elliot.winkler at gmail.com (Elliot Winkler) Date: Sun, 25 Jul 2010 14:47:50 -0500 Subject: [rspec-users] How it would be tested? In-Reply-To: References: <85af84d2-96db-4978-92ea-2519583569e0@b35g2000yqi.googlegroups.com> Message-ID: On 21 July 2010 22:41, tests learner wrote: > But How i would write if i don't know nothing about the code ? Well, you do know something about the code. You don't know what the code is exactly, but you should have a overall grasp of the different aspects of the feature you're adding and how people are going to be interacting with the feature. A good way to think about your app (which has become popular thanks to stuff like Cucumber) is a "top-down" approach. So, you'd start with what the people using your app are going to see in different cases. For each case, you think about what the view is going to do to show the user the right thing. Then you think about what the controller is going to do so the view has what it needs to show the right thing. Then you think about what the model is going to do so that the controller has what *it* needs. Which tools you use to test the different parts of your app is another matter, and you can look further into that as you go along, but I've always found the top-down approach to be a good way to keep your head straight and not get lost in all the details. So.. getting back to your example. To expound on what Costa is saying, if you're writing a model method that runs a query, then don't worry about how what you put in the method or what query is going to be run, at first. You're just thinking about scenarios, and what sort of data you want the method to return in these scenarios. To write the tests, you'll want to populate your test database with some records that correspond to the scenarios that you want to test. Ideally, you also include records that don't fit inside the scenario. Then in your tests you call the method you're testing and verify that the records that should be returned, are, and the ones that shouldn't, aren't. That should at least solve the model side of things. -- Elliot On Sat, Jul 24, 2010 at 9:10 PM, Costa Shapiro wrote: > Alright, as far as I know, the most common approach is to make up some > data for each controller spec, and one of the techniques for doing > this is fixtures (e.g. found in rails) -- another is the mocks, of > course. > Fixtures aren't exactly the hottest offer today, but to me, they are > probably the easiest choice for those messages of yours. > > So, I suppose you may want to type in some message data in the > corresponding fixture file. (see > http://ar.rubyonrails.org/classes/Fixtures.html etc). > If you insist on mocking the messages, that would primarily go into > before :all block. > > Then, in the blocks like 'it "should see all public messages"' you > make requests with the correctly mocked user and check the returned > messages versus the test data (you know which messages are supposed to > return). > > Good luck, > Costa. > > > On 21 July 2010 22:41, tests learner wrote: > > Costa Shapiro, > > > > Thank you for paying atention. > > > > But How i would write if i don't know nothing about the code ? > > > > My problem is: > > I have a messages listing section that will differ according of type > > of user and according with message permission. > > I have messages that are public and private. > > Anyone can see public messages. > > The private messages only can be accessed by who participate on them > > and users that have Owner role on system. > > > > How it would be tested ? > > Since my listing have to list: > > if user not owner: > > - public messages + messages that the user can view because he > > participate on them > > if user is owner: > > - all messages. > > > > So i think the behavior that i have to spec is: > > > > context "guests" do (for ex.) > > before(:all) do > > #mock a guest here > > end > > it "should see all public messages" > > it "should see all messages that participate" > > end > > > > context "owners" do > > before(:all) do > > #mock a owner here > > end > > it "should see all messages" > > end > > > > > > Right? > > I'll be grateful, if you could give any hint about the spec code. > > > > > > Greets, > > > > > > > > On 21 jul, 17:24, Costa Shapiro wrote: > >> Dear Mr. Learner, > >> > >> Please note that while very similar in functionality, specs' philosophy > >> differs from tests' (especially from non-TDD ones). > >> That is, you write spec first, see it fail, and write some code to make > it > >> pass. > >> If you happen to write any implementation code first, you should > disregard > >> it while writing a spec. > >> You may find BDD reading in abundance on the internets. > >> > >> To get a more substantial reply, I think you might want to describe what > you > >> want your code to do in plain English, and the community will hopefully > help > >> you to express that in rspec. > >> > >> Cheers, > >> Costa. > >> > >> On 12 July 2010 13:35, tests learner wrote: > >> > >> > Hello all. > >> > >> > I'm working with rails and came to a situation that i cannot imagine > >> > how to test this. > >> > >> > Given i have an index action that retrieves me a collection of > >> > objects. > >> > But some of them have especific permissions. > >> > >> > My index action act like this: > >> > - retrieve public objects. > >> > - retrieve permission 1 objects. > >> > - retrieve permission 2 objects. > >> > >> > So i have to write 3 tests. > >> > >> > it "should retrieve public objects" > >> > >> > context "permission 1" > >> > it " should retrieve permission 1 objects" > >> > context "permission 2" > >> > it "should retrieve permission 2 objects" > >> > >> > Until here no problems because only conditional tests and method > >> > calls. > >> > >> > But how i would test the "Index.retrieve_objects_from_permission1" ? > >> > >> > supose i have > >> > >> > class Index < ActiveRecord::Base > >> > has_many :permissions > >> > def self.retrieve_objects_from_permission1 > >> > Index.all(:conditions => "permissions.id = 1", :include > >> > => :permissions) > >> > end > >> > >> > def has_permission1 > >> > !self.permissions.find_by_id(1).nil? > >> > end > >> > end > >> > >> > My Index.retrieve_objects_from_permission1 would be: > >> > >> > it "should retrieve objects that have permission 1" do > >> > @collection = Index.retrieve_objects_from_permission1 > >> > @collection.each do |c| > >> > c.has_permission1.should == true > >> > end > >> > end > >> > >> > Is it right? ( I didn't see it before on other's code, so i don't > >> > think it's right.) > >> > >> > Sorry for my poor english. i hope I have been clear enough. > >> > >> > Thank you :) > >> > _______________________________________________ > >> > rspec-users mailing list > >> > rspec-us... at rubyforge.org > >> >http://rubyforge.org/mailman/listinfo/rspec-users > >> > >> > >> > >> _______________________________________________ > >> rspec-users mailing list > >> rspec-us... at rubyforge.orghttp:// > rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ashley.moran at patchspace.co.uk Mon Jul 26 03:31:21 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Mon, 26 Jul 2010 08:31:21 +0100 Subject: [rspec-users] Formatting shared example descriptions with test data Message-ID: <5081B0DE-D18A-4FFE-AD77-BBAF4ADF2B22@patchspace.co.uk> Hi I'm back again, and still on a quest to tame shared example to do my bidding. This time what I'm wondering is... is there any way to format shared example specdoc description output with data passed in with #let, or otherwise? eg: How do I get "1" and "2" into either of the placeholders here? shared_examples_for "Comparable" do describe "comparing " do it "defines equality for " do object.should eq object end end end describe Integer do it_should_behave_like "Comparable" do let(:object) { 1 } end it_should_behave_like "Comparable" do let(:object) { 2 } end end (If I had to duplicate the 1 and 2 that wouldn't be the end of the world, as long as the syntax for including the shared examples was simple enough.) Cheers Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From ashley.moran at patchspace.co.uk Mon Jul 26 03:55:10 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Mon, 26 Jul 2010 08:55:10 +0100 Subject: [rspec-users] RSpec 2 example group block scope Message-ID: <97BED45E-CAA6-4EF2-9105-A7528FC9CAE2@patchspace.co.uk> Hi again As part of the refactoring I'm doing, I'm writing out quite a bit of metaprogramming. The easiest way to prove constant lookup is working is to create a new class in an example group, and use its name. But the scope of the example group definition appears to be the containing module, which gives the following behaviour: module MyModule describe "MyClass" do class TestClass; end # This passes it "has access to the test class" do expect { TestClass }.to_not raise_error end # This fails it "hides the test class somewhere?" do TestClass.name.should_not eq "MyModule::TestClass" end end end module MyModule describe "MyClass doing something else" do # This fails it "has a different scope to the example above" do expect { TestClass }.to raise_error(NameError) end end end I've got a few questions: * Is this intended behaviour, or just merely the way RSpec 2 happens to work? * Would a more unique scope be useful? (To me it would, obviously... don't know about the tradeoff in general though) * Has this changed since RSpec 1.3? (I guess I could install and find out...) Cheers Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From win at wincent.com Mon Jul 26 03:55:55 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 26 Jul 2010 09:55:55 +0200 Subject: [rspec-users] Formatting shared example descriptions with test data In-Reply-To: <5081B0DE-D18A-4FFE-AD77-BBAF4ADF2B22@patchspace.co.uk> References: <5081B0DE-D18A-4FFE-AD77-BBAF4ADF2B22@patchspace.co.uk> Message-ID: El 26/07/2010, a las 09:31, Ashley Moran escribi?: > I'm back again, and still on a quest to tame shared example to do my bidding. This time what I'm wondering is... is there any way to format shared example specdoc description output with data passed in with #let, or otherwise? eg: How do I get "1" and "2" into either of the placeholders here? > > shared_examples_for "Comparable" do > describe "comparing " do > it "defines equality for " do > object.should eq object > end > end > end > > describe Integer do > it_should_behave_like "Comparable" do > let(:object) { 1 } > end > it_should_behave_like "Comparable" do > let(:object) { 2 } > end > end > > (If I had to duplicate the 1 and 2 that wouldn't be the end of the world, as long as the syntax for including the shared examples was simple enough.) Seems to me that including the same shared example group twice in the same "describe" block is a bit of an abuse, to be honest. I don't think it was ever really intended to be used in that way. Your shared_examples_for should be written in such a way that they don't need to reference ""; ie: shared_examples_for "Comparable" do it 'defines equality' do subject.should eq(subject) end end And then you use it like this: describe Integer do [1, 2].each do |i| describe i do it_should_behave_like 'Comparable' end end end Obviously this is a toy example that you've given us, and I don't see why you'd want to test 1 and 2 like that, but for the purposes of illustration... The specdoc output for that would look like: Integer 1 it should behave like Comparable defines equality 2 it should behave like Comparable defines equality I know you probably have some real example in mind hiding behind that toy example, but I believe anything you want to test can be written in the same way (ie. without needing to inject the "" into your shared examples). Cheers, Wincent From ashley.moran at patchspace.co.uk Mon Jul 26 08:09:44 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Mon, 26 Jul 2010 13:09:44 +0100 Subject: [rspec-users] Formatting shared example descriptions with test data In-Reply-To: References: <5081B0DE-D18A-4FFE-AD77-BBAF4ADF2B22@patchspace.co.uk> Message-ID: <9EA40449-A7B5-4AC3-871F-7B04B5C2FDF5@patchspace.co.uk> On Jul 26, 2010, at 8:55 am, Wincent Colaiuta wrote: > Seems to me that including the same shared example group twice in the same "describe" block is a bit of an abuse, to be honest. I don't think it was ever really intended to be used in that way. You're right, it clearly wasn't intended for this. I'm trying to find the best way to express the behaviour I want without bending the current syntax of RSpec too much. This is indeed a toy example, so let me explain the real situation in more detail. I'm doing a small side project to make a checklist app. As part of that, I'm trying to extract out a library similar to Naked Objects[1]. One of the things that can be factored out is collections inside entities. So I currently have, as examples: class User extend DomainLib::Entity::ClassExtensions include DomainLib::Entity::InstanceExtensions collection :checklist_templates, of: :checklist_template, class_name: "ChecklistTemplate" end and class ChecklistTemplate extend DomainLib::Entity::ClassExtensions include DomainLib::Entity::InstanceExtensions collection :items, of: :item, class_name: "ChecklistTemplateItem" end Now one of the thing that bugs me about using ORM (eg ActiveRecord, DataMapper) features for this is you're then faced with the dilemma of do you do an integration test of the collection functionality, which duplicates a lot of the testing effort put into the ORM, or do you mock this out, and risk having false positives because the ORM behaves differently than your test setup assumes? The solution I'm playing with is to extract shared contract (ie shared example groups) that you can mix into a spec for a host class (eg User, Checklist) above to prove the feature (here collections) works, without reference to the implementation. (The specs inside DomainLib prove the general case.) With the help of this spec_helper incantation: module SpecHelperObjectExtensions def contract(name, &block) shared_examples_for(name, &block) end end include SpecHelperObjectExtensions RSpec.configure do |c| c.alias_it_should_behave_like_to(:it_satisfies_contract, 'satisfies contract:') end I've already been able to extracted contract, which is for Representation (basically, a view object that isn't much more than a Struct): # Params: # * representation_class # * properties contract "Representation" do # ... # Setup and other examples omitted # ... describe "#==" do it "is true for Representations with the equal attributes" do representation_class.new(default_attributes).should eq representation_class.new(default_attributes) end it "is false if any property is different" do properties.each do |property| representation_class.new(default_attributes).should_not eq( representation_class.new(default_attributes_with_different_value_for(property)) ) end end end end This is fine for a class, but the behaviour I want to prove with a Collection needs to be mixed in once per collection, eg (the last two are made up): describe User do it_satisfies_contract "Entity Collection", for: "checklist_templates" it_satisfies_contract "Entity Collection", for: "groups" it_satisfies_contract "Entity Collection", for: "delegated_actions" end > describe Integer do > [1, 2].each do |i| > describe i do > it_should_behave_like 'Comparable' > end > end > end > > ... > > I know you probably have some real example in mind hiding behind that toy example, but I believe anything you want to test can be written in the same way (ie. without needing to inject the "" into your shared examples). So as you can see, in the real (non-toy) example there's no object to be described: it's an aspect of behaviour of the test subject, and one than can occur N times. I'm aware that I'm twisting RSpec quite a bit to try to achieve this. If you (or anyone) have any thoughts though, I'd love to hear them. This one is messing with my head a bit :) Cheers Ash [1] http://www.nakedobjects.org/ -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From win at wincent.com Mon Jul 26 10:44:26 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 26 Jul 2010 16:44:26 +0200 Subject: [rspec-users] Formatting shared example descriptions with test data In-Reply-To: <9EA40449-A7B5-4AC3-871F-7B04B5C2FDF5@patchspace.co.uk> References: <5081B0DE-D18A-4FFE-AD77-BBAF4ADF2B22@patchspace.co.uk> <9EA40449-A7B5-4AC3-871F-7B04B5C2FDF5@patchspace.co.uk> Message-ID: El 26/07/2010, a las 14:09, Ashley Moran escribi?: > The solution I'm playing with is to extract shared contract (ie shared example groups) that you can mix into a spec for a host class (eg User, Checklist) above to prove the feature (here collections) works, without reference to the implementation. (The specs inside DomainLib prove the general case.) > > With the help of this spec_helper incantation: > > module SpecHelperObjectExtensions > def contract(name, &block) > shared_examples_for(name, &block) > end > end > include SpecHelperObjectExtensions Personally I wouldn't do this. It makes it harder for anybody coming to your project to understand what's going on, because they see this "contract 'foo' do" construct and don't know what it is unless they dig into your spec_helper. If you really want the word contract to appear in there I would just write the shared examples like this: shared_examples_for 'representation contract' do ... end > RSpec.configure do |c| > c.alias_it_should_behave_like_to(:it_satisfies_contract, 'satisfies contract:') > end And if you go with names like "representation contract" then you might want your alias to be just "it_satisifies" instead... > it "is false if any property is different" do > properties.each do |property| > representation_class.new(default_attributes).should_not eq( > representation_class.new(default_attributes_with_different_value_for(property)) > ) > end > end So if I'm reading you correctly, this is where the "aspect of behavior that can occur N times" comes in, right? AFAIK the typical way to do this is via "macros" (ie. generating examples on the fly, typically keeping to examples of one assertion per iteration of the loop). So it's just a minor tweak of what you've got there: properties.each do |property| it "is false if #{property} is different" do ... end end But alas, this pattern won't work with shared example groups. I don't know of any way to pass the "properties" variable in this case, and even if you could it wouldn't work anyway because, AFAIK, the shared example group is itself only evaluated once when the file is first read. It isn't re-evaluted each time it is included in another example group. At least, that's my understanding of it. I might be wrong about that. So, looks like you're stuck with having multiple assertions inside a single "it" block. > This is fine for a class, but the behaviour I want to prove with a Collection needs to be mixed in once per collection, eg (the last two are made up): > > describe User do > it_satisfies_contract "Entity Collection", for: "checklist_templates" > it_satisfies_contract "Entity Collection", for: "groups" > it_satisfies_contract "Entity Collection", for: "delegated_actions" > end Here the "standard" way of parametrizing this would be via blocks ("standard" in inverted commas because the ability to pass a block here is such a recent addition to RSpec). Cheers, Wincent From nathanvda at gmail.com Mon Jul 26 09:52:53 2010 From: nathanvda at gmail.com (nathanvda) Date: Mon, 26 Jul 2010 06:52:53 -0700 (PDT) Subject: [rspec-users] beginner questions: parametrize tests and disable tests (skippy?) Message-ID: Hi there, i have two very specific questions. I am writing an application to send sms-es. Now i would like to be able, somehow, to disable the part of my tests that actually sends the sms-es. My code is tested, but to actually test sending the sms-es, i need to test the configuration. So it is needed to test that too, but not as frequently. E.g. our cruisecontrol would need to do it only once per day or per week, but not every time somebody checks in. For test::unit there exists a solution: http://github.com/jm/skippy Is there a similar solution for Rspec? Or how do you guys solve this? Secondly i have a small look-up table, and i want to check that my function gives the correct result. I would like something like the commented part, because if one lookup- translation would fail, we get an appropriate message: # STATUS_EXPECTED_TRANSLATIONS.each |tr| do # it "should translate #tr[0]} to success" do # result = translate_status(tr[0]) # result.should == tr[1] # end # end it "should translate received statuses" do STATUS_EXPECTED_TRANSLATIONS.each do |tr| controller.send('translate_status_to_envelope_status', tr[0]).should == tr[1] end end Is that possible? Or what is the advised way to handle/test something like that? From lists at ruby-forum.com Mon Jul 26 12:12:14 2010 From: lists at ruby-forum.com (Bruno Cardoso) Date: Mon, 26 Jul 2010 18:12:14 +0200 Subject: [rspec-users] Problem running RSpec tests with Rails Message-ID: Hi Not sure if this is a RSpec problem or Rails but I believe is more a RSpec situation. What happens is that when I run my RSpecs tests all the BD is recreated, including the "schema_migration" table, because of this I get a problem saying: You have 29 pending migrations: 20100628100855 CreateCustomers 20100628103228 CreateAccounts 20100628172155 CreateCfgEntities ... etc It seems rails notices that the schema_migration tables is empty and that are migration scripts to run. This shouldn't be needed because Rails uses schema.rb to recreate the table, right? I'm using JRuby with JDBC connection by the way. Anyone know how to resolve this? -- Posted via http://www.ruby-forum.com/. From dark.red.and.yellow at googlemail.com Mon Jul 26 12:12:59 2010 From: dark.red.and.yellow at googlemail.com (=?ISO-8859-1?Q?Timo_R=F6=DFner?=) Date: Mon, 26 Jul 2010 09:12:59 -0700 (PDT) Subject: [rspec-users] render_template expectation - surprising pattern matching issue Message-ID: <2fe82824-0691-4cdc-924b-dc6550b3bf74@d17g2000yqb.googlegroups.com> Hey guys, we just found out by accident that rspec seems to apply a pretty confusing mechanism to ensure that a certain template is rendered. To clarify, consider this standard controller spec: # working it 'GET edit' do get :edit, :id => '37' response.should render_template(:edit) end So far, so good. Now to the surprising part: # NOT working it 'GET edit' do get :edit, :id => '37' response.should render_template(:eda) end # -> here's the surprise: working it 'GET edit' do get :edit, :id => '37' response.should render_template(:edi) end Apparently rspec uses a pretty generous pattern matching to ensure that a certain template is rendered. If I had to guess, I'd say that's because rspec wants to ignore path / namespacing / different file endings (html.haml, html.erb and so on). I still think this approach is suboptimal for two reasons: 1.) It violates the principle of least suprise, this behaviour is more like "the biggest surprise possible" - who would have thought that example nr.3 is working? 2.) I can easily imagine a situation where 2 or more actions start with the same letters. In this case, what would happen if you changed the "render_template"-call (i.e. shortening the template name) and remove one action. Wouldnt the specs still be green although one view would be completely missing? 2 questions: 1.) Is this a bug or a feature? 2.) Why not change the pattern matching that it still ignores paths and file endings, but at least tries to match the expected template exactly to the rendered template? From ashley.moran at patchspace.co.uk Mon Jul 26 12:15:47 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Mon, 26 Jul 2010 17:15:47 +0100 Subject: [rspec-users] Formatting shared example descriptions with test data In-Reply-To: References: <5081B0DE-D18A-4FFE-AD77-BBAF4ADF2B22@patchspace.co.uk> <9EA40449-A7B5-4AC3-871F-7B04B5C2FDF5@patchspace.co.uk> Message-ID: On Jul 26, 2010, at 3:44 pm, Wincent Colaiuta wrote: > Personally I wouldn't do this. It makes it harder for anybody coming to your project to understand what's going on, because they see this "contract 'foo' do" construct and don't know what it is unless they dig into your spec_helper. If you really want the word contract to appear in there I would just write the shared examples like this: Actually, this doesn't bother me. All the commercial development I do is pair-programmed, so it doesn't take long for anyone new to a project to pick things like these up. I prefer to improve the semantics at the expense of some initial learning cost. (As it happens, this isn't a commercial project anyway, it's just something I'm doing on the side for my own benefit.) > So if I'm reading you correctly, this is where the "aspect of behavior that can occur N times" comes in, right? AFAIK the typical way to do this is via "macros" (ie. generating examples on the fly, typically keeping to examples of one assertion per iteration of the loop). So it's just a minor tweak of what you've got there: > > properties.each do |property| > it "is false if #{property} is different" do > ... > end > end If you mean by using a custom matcher in there, then yeah, I get you. But as this is more extensive, shared examples (which prove many individual pieces of behaviour) seemed a better fit than a matcher (which are intended to prove just one). > But alas, this pattern won't work with shared example groups. I don't know of any way to pass the "properties" variable in this case, and even if you could it wouldn't work anyway because, AFAIK, the shared example group is itself only evaluated once when the file is first read. It isn't re-evaluted each time it is included in another example group. At least, that's my understanding of it. I might be wrong about that. So, looks like you're stuck with having multiple assertions inside a single "it" block. Hmmm, if that's the case, then this approach won't work anyway. But I'll investigate... it depends on the implementation. This is one of the things I want to find out. >> This is fine for a class, but the behaviour I want to prove with a Collection needs to be mixed in once per collection, eg (the last two are made up): >> >> describe User do >> it_satisfies_contract "Entity Collection", for: "checklist_templates" >> it_satisfies_contract "Entity Collection", for: "groups" >> it_satisfies_contract "Entity Collection", for: "delegated_actions" >> end > > Here the "standard" way of parametrizing this would be via blocks ("standard" in inverted commas because the ability to pass a block here is such a recent addition to RSpec). Yeah, I'm doing that to get the necessary objects inside the shared example. But as you pointed out, the scope inside example groups and inside the examples themselves are very different. Cheers Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From phillipkoebbe at gmail.com Mon Jul 26 12:22:21 2010 From: phillipkoebbe at gmail.com (Phillip Koebbe) Date: Mon, 26 Jul 2010 11:22:21 -0500 Subject: [rspec-users] render_template expectation - surprising pattern matching issue In-Reply-To: <2fe82824-0691-4cdc-924b-dc6550b3bf74@d17g2000yqb.googlegroups.com> References: <2fe82824-0691-4cdc-924b-dc6550b3bf74@d17g2000yqb.googlegroups.com> Message-ID: <4C4DB63D.4090502@gmail.com> On 2010-07-26 11:12 AM, Timo R??ner wrote: > Hey guys, > > we just found out by accident that rspec seems to apply a pretty > confusing mechanism to ensure that a certain template is rendered. > > To clarify, consider this standard controller spec: > > # working > it 'GET edit' do > get :edit, :id => '37' > response.should render_template(:edit) > end > > So far, so good. Now to the surprising part: > > # NOT working > it 'GET edit' do > get :edit, :id => '37' > response.should render_template(:eda) > end > > # -> here's the surprise: working > it 'GET edit' do > get :edit, :id => '37' > response.should render_template(:edi) > end > > Apparently rspec uses a pretty generous pattern matching to ensure > that a certain template is rendered. > > If I had to guess, I'd say that's because rspec wants to ignore path / > namespacing / different file endings (html.haml, html.erb and so on). > > I still think this approach is suboptimal for two reasons: > > 1.) It violates the principle of least suprise, this behaviour is more > like "the biggest surprise possible" - who would have thought that > example nr.3 is working? > > 2.) I can easily imagine a situation where 2 or more actions start > with the same letters. In this case, what would happen if you changed > the "render_template"-call (i.e. shortening the template name) and > remove one action. > Wouldnt the specs still be green although one view would be completely > missing? > > 2 questions: > > 1.) Is this a bug or a feature? > > 2.) Why not change the pattern matching that it still ignores paths > and file endings, but at least tries to match the expected template > exactly to the rendered template? > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users I've experienced a bit of pain with making sure the right view gets rendered. Initially, I was doing essentially what you are doing, but noticed that the specs would pass even if I didn't render the view (ie, the view wasn't there). Then I discovered integrate_views, which helped immensely in that regard, until I later discovered that I had to mock and stub everything that the view expected. Hated that. I've since started using something that is not quite as unobtrusive as I'd like, but I much prefer the results. I don't integrate_views any more and I set an expectation on the controller to render. Something like: describe 'get :index' do it 'should render the index view' do controller.should_receive(:render).with(:index) get :index end end The unfortunate part of this is that I must then explicitly render the view in the controller action: def index ... render :index end I wish I didn't have to do it that way, but so far, this is the best I can do to balance specing the controller with keeping things isolated. I openly admit there might be a better solution and I may very well have overlooked something obvious. I didn't spend a lot of time trying to get this figured out correctly, so there may be a better way. Peace, Phillip From lille.penguini at gmail.com Mon Jul 26 12:34:49 2010 From: lille.penguini at gmail.com (Lille) Date: Mon, 26 Jul 2010 09:34:49 -0700 (PDT) Subject: [rspec-users] [newbie] rspec, validations and factory_girl Message-ID: Hi, class B < ActiveRecord::Base belongs_to :a validates_numericality_of :some_attribute, :greater_than => 0, :allow_blank=>true def some_attribute a.numeric_attr * read_attribute(:some_attribute) end ... If I create an instance of my class B in rspec with factory_girl w.out a parent (but not required!) instance of class A, I get the following error: "undefined method `numeric_attr' for nil:NilClass". Why? Is this an apparent idiosyncrasy of using rspec and factory_girl together? Thanks, Lille From win at wincent.com Mon Jul 26 11:37:32 2010 From: win at wincent.com (Wincent Colaiuta) Date: Mon, 26 Jul 2010 17:37:32 +0200 Subject: [rspec-users] beginner questions: parametrize tests and disable tests (skippy?) In-Reply-To: References: Message-ID: El 26/07/2010, a las 15:52, nathanvda escribi?: > For test::unit there exists a solution: http://github.com/jm/skippy > Is there a similar solution for Rspec? > Or how do you guys solve this? The way to do the "Skippy" thing under RSpec 2 will be filtering: http://blog.davidchelimsky.net/2010/06/14/filtering-examples-in-rspec-2/ > Secondly i have a small look-up table, and i want to check that my > function gives the correct result. > > I would like something like the commented part, because if one lookup- > translation would fail, we get an appropriate message: > > # STATUS_EXPECTED_TRANSLATIONS.each |tr| do > # it "should translate #tr[0]} to success" do > # result = translate_status(tr[0]) > # result.should == tr[1] > # end > # end > > it "should translate received statuses" do > STATUS_EXPECTED_TRANSLATIONS.each do |tr| > controller.send('translate_status_to_envelope_status', > tr[0]).should == tr[1] > end > end > > Is that possible? Or what is the advised way to handle/test something > like that? Yes, it's possible, but generating examples is a technique to be used sparingly, only when it makes sense to do so. Generally, the trade off between "explicit" and "DRY" is different in specs than it is in code. In specs we value explicitness and simplicity above DRYness (the specs have to be bug free, they have to be readable, they should be a document -- ie. a specification -- of the behavior of the code, and perhaps most importantly of all, you want to be able to click on a failing spec's file and line number and be taken straight to it and know which spec failed without any ambiguity) whereas in code DRYness is given a much higher value. So I don't know how many entires you have in your STATUS_EXPECTED_TRANSLATIONS, but if the number is small enough, I'd suggest that you just list the translations explicitly, repeating the "it" block for each translation. Cheers, Wincent From ashley.moran at patchspace.co.uk Mon Jul 26 12:50:05 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Mon, 26 Jul 2010 17:50:05 +0100 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: References: Message-ID: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> On Jul 26, 2010, at 5:12 pm, Bruno Cardoso wrote: > Not sure if this is a RSpec problem or Rails but I believe is more a > RSpec situation. > > What happens is that when I run my RSpecs tests all the BD is recreated, > > ... > > Anyone know how to resolve this? Hi Bruno Are you running `rake spec` as opposed to the spec command? The default Rails spec task depends on the "db:test:prepare" task, which bombs your DB. I fixed this in my project with a file "lib/tasks/rspec_fixes.rake": class Rake::Task def overwrite(&block) @actions.clear enhance(&block) end end Rake::Task['db:test:prepare'].overwrite do # We don't want to run migrations or load the schema!!! end HTH Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From dchelimsky at gmail.com Mon Jul 26 13:06:10 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 26 Jul 2010 12:06:10 -0500 Subject: [rspec-users] [newbie] rspec, validations and factory_girl In-Reply-To: References: Message-ID: <8B0FC0F1-6B62-4ABE-8D28-9EF20FC57897@gmail.com> On Jul 26, 2010, at 11:34 AM, Lille wrote: > Hi, > > class B < ActiveRecord::Base > belongs_to :a > validates_numericality_of :some_attribute, :greater_than => > 0, :allow_blank=>true > > def some_attribute > a.numeric_attr * read_attribute(:some_attribute) > end > ... > > If I create an instance of my class B in rspec with factory_girl w.out > a parent (but not required!) It may not be a business requirement, but the some_attribute method above requires it's existence in order to run without error. Try: def some_attribute return nil unless a a.numeric_attr * read_attribute(:some_attribute) end HTH, David > instance of class A, I get the following > error: "undefined method `numeric_attr' for nil:NilClass". > > Why? Is this an apparent idiosyncrasy of using rspec and factory_girl > together? > Thanks, > > Lille From dchelimsky at gmail.com Mon Jul 26 13:09:15 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 26 Jul 2010 12:09:15 -0500 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: References: Message-ID: On Jul 26, 2010, at 11:12 AM, Bruno Cardoso wrote: > Hi > > Not sure if this is a RSpec problem or Rails but I believe is more a > RSpec situation. > > What happens is that when I run my RSpecs tests all the BD is recreated, > including the "schema_migration" table, because of this I get a problem > saying: > > You have 29 pending migrations: > 20100628100855 CreateCustomers > 20100628103228 CreateAccounts > 20100628172155 CreateCfgEntities > ... > etc > > It seems rails notices that the schema_migration tables is empty and > that are migration scripts to run. This shouldn't be needed because > Rails uses schema.rb to recreate the table, right? The test database, yes, but it won't get that far if you have any pending migrations in the development database. If you run "rake spec --trace" you'll see that it runs db:test:prepare, which runs db:abort_if_pending_migrations. HTH, David > > I'm using JRuby with JDBC connection by the way. > > Anyone know how to resolve this? From dchelimsky at gmail.com Mon Jul 26 13:13:44 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 26 Jul 2010 12:13:44 -0500 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> References: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> Message-ID: On Jul 26, 2010, at 11:50 AM, Ashley Moran wrote: > > On Jul 26, 2010, at 5:12 pm, Bruno Cardoso wrote: > >> Not sure if this is a RSpec problem or Rails but I believe is more a >> RSpec situation. >> >> What happens is that when I run my RSpecs tests all the BD is recreated, >> >> ... >> >> Anyone know how to resolve this? > > Hi Bruno > > Are you running `rake spec` as opposed to the spec command? The default Rails spec task depends on the "db:test:prepare" task, which bombs your DB. The test DB, not the development DB, right? If it's bombing your dev DB then please file a bug report and we can sort it out. > I fixed this in my project with a file "lib/tasks/rspec_fixes.rake": > > class Rake::Task > def overwrite(&block) > @actions.clear > enhance(&block) > end > end > > Rake::Task['db:test:prepare'].overwrite do Another approach would be: Rake::Task['spec'].prerequisites.clear Cheers, David > # We don't want to run migrations or load the schema!!! > end > > HTH > > Ash > > -- > http://www.patchspace.co.uk/ > http://www.linkedin.com/in/ashleymoran > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From lists at ruby-forum.com Mon Jul 26 13:36:17 2010 From: lists at ruby-forum.com (Bruno Cardoso) Date: Mon, 26 Jul 2010 19:36:17 +0200 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: References: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> Message-ID: <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> Thanks for the answers. What both solutions (from Ashley and David) do is not modify the BD in anyway, so nothing gets dropped and nothing is created. This resolves the problem but what if I want a clean installation in each test run? Is there a way to keep my "schema_migrations" table or remove the check for migration scripts? I would still like to recreate the rest of the tables. -- Posted via http://www.ruby-forum.com/. From lists at ruby-forum.com Mon Jul 26 13:40:40 2010 From: lists at ruby-forum.com (Bruno Cardoso) Date: Mon, 26 Jul 2010 19:40:40 +0200 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> References: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> Message-ID: Bruno Cardoso wrote: > Thanks for the answers. > > What both solutions (from Ashley and David) do is not modify the BD in > anyway, so nothing gets dropped and nothing is created. This resolves > the problem but what if I want a clean installation in each test run? Is > there a way to keep my "schema_migrations" table or remove the check for > migration scripts? I would still like to recreate the rest of the > tables. By the way, I'm using: "rake spec --trace" and the result was: ** Invoke spec (first_time) ** Invoke db:test:prepare (first_time) ** Invoke db:abort_if_pending_migrations (first_time) ** Invoke environment ** Execute db:abort_if_pending_migrations You have 12 pending migrations: 20100628100855 CreateCustomers ... Run "rake db:migrate" to update your database then try again. -- Posted via http://www.ruby-forum.com/. From lille.penguini at gmail.com Mon Jul 26 13:51:14 2010 From: lille.penguini at gmail.com (Lille) Date: Mon, 26 Jul 2010 10:51:14 -0700 (PDT) Subject: [rspec-users] [newbie] rspec, validations and factory_girl In-Reply-To: <8B0FC0F1-6B62-4ABE-8D28-9EF20FC57897@gmail.com> References: <8B0FC0F1-6B62-4ABE-8D28-9EF20FC57897@gmail.com> Message-ID: <61ec2b74-3075-4fac-a326-989aaed7a029@j8g2000yqd.googlegroups.com> OK. On a Rails note, this seems to suggest that attributes are checked from their accessors before the save, whereas I had assumed my some_attribute accessor would not be called at all during validation... (Thank you David, this is one of the better groups I've lately monitored, and a fine complement to your book...) Thanks, Lille On Jul 26, 1:06?pm, David Chelimsky wrote: > On Jul 26, 2010, at 11:34 AM, Lille wrote: > > > Hi, > > > class B < ActiveRecord::Base > > ?belongs_to :a > > ?validates_numericality_of :some_attribute, :greater_than => > > 0, :allow_blank=>true > > > ?def some_attribute > > ? ? ?a.numeric_attr * read_attribute(:some_attribute) > > ?end > > ?... > > > If I create an instance of my class B in rspec with factory_girl w.out > > a parent (but not required!) > > It may not be a business requirement, but the some_attribute method above requires it's existence in order to run without error. > > Try: > > def some_attribute > ? return nil unless a > ? a.numeric_attr * read_attribute(:some_attribute) > end > > HTH, > David > > > instance of class A, I get the following > > error: "undefined method `numeric_attr' for nil:NilClass". > > > Why? Is this an apparent idiosyncrasy of using rspec and factory_girl > > together? > > Thanks, > > > Lille > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From ashley.moran at patchspace.co.uk Mon Jul 26 17:14:40 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Mon, 26 Jul 2010 22:14:40 +0100 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> References: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> Message-ID: On 26 Jul 2010, at 6:36 PM, Bruno Cardoso wrote: > What both solutions (from Ashley and David) do is not modify the BD in > anyway, so nothing gets dropped and nothing is created. This resolves > the problem but what if I want a clean installation in each test run? Is > there a way to keep my "schema_migrations" table or remove the check for > migration scripts? I would still like to recreate the rest of the > tables. One way is to avoid rake entirely - you could run the specs with `spec spec` or even just use autotest[1]. If you want to just empty the data from the tables you need database_cleaner[2]. If you want the database rebuilt as necessary when migrations change, you could use my database_resetter[3], plug plug :D Let me know if you're trying to do something other than one of these. (It's late, I have a habit of talking nonsense when I'm tired...) HTH Ash [1] eg http://ph7spot.com/musings/getting-started-with-autotest [2] http://github.com/bmabey/database_cleaner [3] http://rubygems.org/gems/database_resetter -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From dchelimsky at gmail.com Mon Jul 26 22:32:09 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Mon, 26 Jul 2010 21:32:09 -0500 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> References: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> Message-ID: On Jul 26, 2010, at 12:36 PM, Bruno Cardoso wrote: > Thanks for the answers. > > What both solutions (from Ashley and David) do is not modify the BD in > anyway, so nothing gets dropped and nothing is created. This resolves > the problem but what if I want a clean installation in each test run? So is your goal here to have the rake task(s) ignore the fact that you have pending migrations, but still have it reset the test database so it's schema looks like the development database schema? > Is > there a way to keep my "schema_migrations" table or remove the check for > migration scripts? I would still like to recreate the rest of the > tables. > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From nathanvda at gmail.com Tue Jul 27 05:05:06 2010 From: nathanvda at gmail.com (nathanvda) Date: Tue, 27 Jul 2010 02:05:06 -0700 (PDT) Subject: [rspec-users] beginner questions: parametrize tests and disable tests (skippy?) In-Reply-To: References: Message-ID: <61050877-22ab-43d3-8fb2-87594c5f0364@r10g2000vbc.googlegroups.com> > > The way to do the "Skippy" thing under RSpec 2 will be filtering: > > http://blog.davidchelimsky.net/2010/06/14/filtering-examples-in-rspec-2/ Awesome! Just what i need :) > > Generally, the trade off between "explicit" and "DRY" is different in specs than it is in code. In specs we value explicitness and simplicity above DRYness (the specs have to be bug free, they have to be readable, they should be a document -- ie. a specification -- of the behavior of the code, and perhaps most importantly of all, you want to be able to click on a failing spec's file and line number and be taken straight to it and know which spec failed without any ambiguity) whereas in code DRYness is given a much higher value. > > So I don't know how many entires you have in your STATUS_EXPECTED_TRANSLATIONS, but if the number is small enough, I'd suggest that you just list the translations explicitly, repeating the "it" block for each translation. > Thank you for your advice! It makes sense to me, and the list of options is indeed limited ;) From lists at ruby-forum.com Tue Jul 27 05:10:53 2010 From: lists at ruby-forum.com (Bruno Cardoso) Date: Tue, 27 Jul 2010 11:10:53 +0200 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: References: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> Message-ID: David Chelimsky wrote: > On Jul 26, 2010, at 12:36 PM, Bruno Cardoso wrote: > >> Thanks for the answers. >> >> What both solutions (from Ashley and David) do is not modify the BD in >> anyway, so nothing gets dropped and nothing is created. This resolves >> the problem but what if I want a clean installation in each test run? > > So is your goal here to have the rake task(s) ignore the fact that you > have pending migrations, but still have it reset the test database so > it's schema looks like the development database schema? Exactly. I'm ok with the previous solution, it's something we can do but I would like to know what I could do if I wanted to go by my first plan. -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Tue Jul 27 06:37:57 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Tue, 27 Jul 2010 05:37:57 -0500 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: References: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> Message-ID: <7B02F119-9E7B-451D-B6AA-A689885B0285@gmail.com> On Jul 27, 2010, at 4:10 AM, Bruno Cardoso wrote: > David Chelimsky wrote: >> On Jul 26, 2010, at 12:36 PM, Bruno Cardoso wrote: >> >>> Thanks for the answers. >>> >>> What both solutions (from Ashley and David) do is not modify the BD in >>> anyway, so nothing gets dropped and nothing is created. This resolves >>> the problem but what if I want a clean installation in each test run? >> >> So is your goal here to have the rake task(s) ignore the fact that you >> have pending migrations, but still have it reset the test database so >> it's schema looks like the development database schema? > > Exactly. OK. This is not Rails' intent (which is why 'db:abort_if_pending_migrations' is a prereq of 'db:test:prepare'), but you can use the same technique I described earlier on 'db:test:prepare' instead of 'spec': Rake::Task['db:test:prepare'].clear_prerequisites Now you should get what you're looking for. Cheers, David > > I'm ok with the previous solution, it's something we can do but I would > like to know what I could do if I wanted to go by my first plan. > -- > 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 Tue Jul 27 07:01:59 2010 From: lists at ruby-forum.com (Bruno Cardoso) Date: Tue, 27 Jul 2010 13:01:59 +0200 Subject: [rspec-users] Problem running RSpec tests with Rails In-Reply-To: <7B02F119-9E7B-451D-B6AA-A689885B0285@gmail.com> References: <2A939E90-6C69-4D5C-AF00-E8A2CEE584C0@patchspace.co.uk> <2622f819d9ae1b6aff56c5a61be3cbc2@ruby-forum.com> <7B02F119-9E7B-451D-B6AA-A689885B0285@gmail.com> Message-ID: David Chelimsky wrote: > On Jul 27, 2010, at 4:10 AM, Bruno Cardoso wrote: > >>> have pending migrations, but still have it reset the test database so >>> it's schema looks like the development database schema? >> >> Exactly. > > OK. This is not Rails' intent (which is why > 'db:abort_if_pending_migrations' is a prereq of 'db:test:prepare'), but > you can use the same technique I described earlier on 'db:test:prepare' > instead of 'spec': > > Rake::Task['db:test:prepare'].clear_prerequisites > > Now you should get what you're looking for. > > Cheers, > David Yeah, it worked exactly like you said. Now I can choose between the two approaches. Thanks. -- Posted via http://www.ruby-forum.com/. From tadatoshi.mailinglist at gmail.com Tue Jul 27 13:18:22 2010 From: tadatoshi.mailinglist at gmail.com (tadatoshi) Date: Tue, 27 Jul 2010 10:18:22 -0700 (PDT) Subject: [rspec-users] 2.0.0.beta.19 -"its" construct doesn't work Message-ID: <66d4d7c1-cd17-43d5-8b5c-4b0261747c86@c38g2000vba.googlegroups.com> I have updated RSpec to 2.0.0.beta.19 and "its" construct that has been working with 2.0.0.beta.18 doesn't work any more. Error message is: implicit argument passing of super from method defined by define_method() is not supported. Specify all arguments explicitly. What is the new syntax? Thank you in advance. From nicholas.wieland at gmail.com Tue Jul 27 21:40:20 2010 From: nicholas.wieland at gmail.com (Nicholas Wieland) Date: Tue, 27 Jul 2010 18:40:20 -0700 Subject: [rspec-users] Testing subdomains Message-ID: <62529D5F-CC48-4E2D-8BF6-46AD8AFB764E@gmail.com> Hi *, is someone using rspec 2 and rails 3 for testing subdomains ? How do I test for example in a route spec tis route ? match 'profile', :to => 'users#profile', :constraints => { :subdomain => /.+/ } TIA, ngw From jarmo.p at gmail.com Wed Jul 28 14:52:17 2010 From: jarmo.p at gmail.com (Jarmo Pertman) Date: Wed, 28 Jul 2010 11:52:17 -0700 (PDT) Subject: [rspec-users] about spec.opts and command line options and global options Message-ID: <9f993fe0-14b2-46b2-87d5-9a472d5f2036@f42g2000yqn.googlegroups.com> Hello! I have some questions/proposals which have been quite time on my mind already. Let's suppose i have files under spec directory with the following structure and contents: # spec/helper.rb module Helper end # spec/my_spec.rb describe Helper do # notice the usage of constant Helper end #spec/spec.opts --require spec/helper If i execute "spec spec\my_spec.rb" then everything works as expected. This solution gives me the possibility not to write all those require statements into each spec file and i'm happy to use it so i can write less duplicate code. But there is a big problem if i want to enter some additional parameters for some specific run. Let's say i'd like to execute this command: spec spec\my_spec.rb -b I would expect this "-b" to merged with all the options from spec.opts, but what actually happens is that all options from spec.opts are ignored, thus the test above will fail because Helper constant is missing. That just doesn't make sense! I also found the place in code where this magic happens: # spec/runner/option_parser.rb def parse_file_options(...) ... if options_file.nil? && File.exist?('spec/spec.opts') && !@argv.any?{|a| a =~ /^\-/ } options_file = 'spec/spec.opts' end ... end So, if there are any command line arguments specified then spec.opts is ignored... Let me bring some more realistic example if you might think that this magic require in spec.opts is bad idea... Let's have a "normal" spec.opts file: # spec.opts --format nested -c This means that i'm using nested formatter with colored output. Not a bad idea, i guess. But now if i want to execute only one example with -e, then my output will not be nested nor colored because of this ignore statement above... again, that doesn't make sense, does it? Also, is there any possibility to have global options - let's say that i want every project on my PC to have nested and colored output - what shall i do? Any easy way to accomplish it programmatically if there's no built-in functionality yet? Why is spec.opts hardcoded to be in spec directory? I would like it to work like rake is searching for rakefiles - searches up in the directory tree until finding rakefile. I would like if spec.opts allowed to enter Ruby code so i wouldn't have to hardcode --require statement paths from working dir, but could use something like File.dirname(__FILE__) + "/helper"... In summary, my proposals for spec.opts would be: 1) Search for spec.opts upwards starting from spec directory. 2) Merge command line options with spec.opts - e.g have higher priority for command line options, BUT preserve spec.opts if they're not overridden. 3) Make spec.opts to handle Ruby code. 4) Allow some way to specify global configuration options for RSpec. I'm using RSpec 1.3.0 and don't know how these situations are handled in RSpec 2 branches. Hopefully my ideas make sense. Jarmo Pertman ----- IT does really matter - http://www.itreallymatters.net From dchelimsky at gmail.com Wed Jul 28 15:27:58 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 28 Jul 2010 14:27:58 -0500 Subject: [rspec-users] about spec.opts and command line options and global options In-Reply-To: <9f993fe0-14b2-46b2-87d5-9a472d5f2036@f42g2000yqn.googlegroups.com> References: <9f993fe0-14b2-46b2-87d5-9a472d5f2036@f42g2000yqn.googlegroups.com> Message-ID: <75734729-7E01-4032-BDAE-9C821DBDCB24@gmail.com> On Jul 28, 2010, at 1:52 PM, Jarmo Pertman wrote: > Hello! > > I have some questions/proposals which have been quite time on my mind > already. > > Let's suppose i have files under spec directory with the following > structure and contents: > # spec/helper.rb > module Helper > end > > # spec/my_spec.rb > describe Helper do # notice the usage of constant Helper > end > > #spec/spec.opts > --require spec/helper > > If i execute "spec spec\my_spec.rb" then everything works as expected. > This solution gives me the possibility not to write all those require > statements into each spec file and i'm happy to use it so i can write > less duplicate code. > > But there is a big problem if i want to enter some additional > parameters for some specific run. Let's say i'd like to execute this > command: > spec spec\my_spec.rb -b > > I would expect this "-b" to merged with all the options from > spec.opts, but what actually happens is that all options from > spec.opts are ignored, thus the test above will fail because Helper > constant is missing. That just doesn't make sense! > > I also found the place in code where this magic happens: > # spec/runner/option_parser.rb > > def parse_file_options(...) > ... > if options_file.nil? && > File.exist?('spec/spec.opts') && > !@argv.any?{|a| a =~ /^\-/ } > options_file = 'spec/spec.opts' > end > ... > end > > So, if there are any command line arguments specified then spec.opts > is ignored... > > Let me bring some more realistic example if you might think that this > magic require in spec.opts is bad idea... > > Let's have a "normal" spec.opts file: > # spec.opts > --format > nested > -c > > This means that i'm using nested formatter with colored output. Not a > bad idea, i guess. > > But now if i want to execute only one example with -e, then my output > will not be nested nor colored because of this ignore statement > above... again, that doesn't make sense, does it? > > Also, is there any possibility to have global options - let's say that > i want every project on my PC to have nested and colored output - what > shall i do? Any easy way to accomplish it programmatically if there's > no built-in functionality yet? > > Why is spec.opts hardcoded to be in spec directory? I would like it to > work like rake is searching for rakefiles - searches up in the > directory tree until finding rakefile. > > I would like if spec.opts allowed to enter Ruby code so i wouldn't > have to hardcode --require statement paths from working dir, but could > use something like File.dirname(__FILE__) + "/helper"... > > In summary, my proposals for spec.opts would be: > 1) Search for spec.opts upwards starting from spec directory. > 2) Merge command line options with spec.opts - e.g have higher > priority for command line options, BUT preserve spec.opts if they're > not overridden. > 3) Make spec.opts to handle Ruby code. > 4) Allow some way to specify global configuration options for RSpec. > > I'm using RSpec 1.3.0 and don't know how these situations are handled > in RSpec 2 branches. > > Hopefully my ideas make sense. I think http://github.com/rspec/rspec-core/blob/master/Upgrade.markdown might answer some of your questions. HTH, David From jarmo.p at gmail.com Wed Jul 28 15:42:34 2010 From: jarmo.p at gmail.com (Jarmo Pertman) Date: Wed, 28 Jul 2010 12:42:34 -0700 (PDT) Subject: [rspec-users] about spec.opts and command line options and global options In-Reply-To: <75734729-7E01-4032-BDAE-9C821DBDCB24@gmail.com> References: <9f993fe0-14b2-46b2-87d5-9a472d5f2036@f42g2000yqn.googlegroups.com> <75734729-7E01-4032-BDAE-9C821DBDCB24@gmail.com> Message-ID: Thank You! If i understand correctly, then all the problems except #3 have been solved in RSpec 2? Nice that there are people with similar thoughts :) Jarmo Pertman ----- IT does really matter - http://www.itreallymatters.net On Jul 28, 10:27?pm, David Chelimsky wrote: > I thinkhttp://github.com/rspec/rspec-core/blob/master/Upgrade.markdownmight answer some of your questions. > > HTH, > David > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From nick.rutherford at gmail.com Wed Jul 28 18:42:23 2010 From: nick.rutherford at gmail.com (nruth) Date: Wed, 28 Jul 2010 15:42:23 -0700 (PDT) Subject: [rspec-users] rspec 1 - nested examples (in an each block) use the final block variable 4 times instead of each of the 4 once Message-ID: Please correct me if this is fixed in Rspec 2, but in Rspec 1 I have hit upon the following problem (at least thrice, this time it costing me several hours), code is the best example: I have a practice examination system where each record is one of several "subtests" (think tagging rather than subclassing) which is part of a constant string array. I want to test each's behaviour indepently in my specs (since an earlier implementation used STI rather than tagging, and I want to test each kind of test follows the spec) My specs use this approach in parts: describe "#add_question_set_of_type" do MyModule::SUBTESTS.each do |subtest| describe %Q("#{subtest}") do ? specs using subtest end end where SUBTESTS is a constant array of strings. the problem is doing this breaks any blocks that look like let(:subtest) {MyModule.subtest_to_sym(subtest)} or before(:each) do @subtest = MyModule.subtest_to_sym(subtest) end Instead I have to avoid the @ or let examples, and use the more explicit (verbose): MyModule.subtest_to_sym(subtest) using the let or before @ approaches both fail. Using puts within the code (for debugging purposes) I found that the specs were only being exposed to the final value of the array, while I expected (and have seen, or at least assumed from past passes) that all 4 (or so) of the strings were being used to create unique methods on the example group (one per iteration). Is this something that should be: a. avoided, because it's crazy, and written differently b, documented c. investigated further I can provide a more complete example if helpful? Thanks, Nick From dchelimsky at gmail.com Wed Jul 28 20:22:55 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Wed, 28 Jul 2010 19:22:55 -0500 Subject: [rspec-users] rspec 1 - nested examples (in an each block) use the final block variable 4 times instead of each of the 4 once In-Reply-To: References: Message-ID: <815FC805-4DA8-46CB-853B-CC0BAE42B112@gmail.com> On Jul 28, 2010, at 5:42 PM, nruth wrote: > Please correct me if this is fixed in Rspec 2, but in Rspec 1 I have > hit upon the following problem (at least thrice, this time it costing > me several hours), code is the best example: > > I have a practice examination system where each record is one of > several "subtests" (think tagging rather than subclassing) which is > part of a constant string array. I want to test each's behaviour > indepently in my specs (since an earlier implementation used STI > rather than tagging, and I want to test each kind of test follows the > spec) > > My specs use this approach in parts: > > describe "#add_question_set_of_type" do > MyModule::SUBTESTS.each do |subtest| > > describe %Q("#{subtest}") do > ? specs using subtest > end > end > > where SUBTESTS is a constant array of strings. > > the problem is doing this breaks any blocks that look like Where are these blocks, in the outer or inner example group? Please provide a complete example, including everything I need to run and see the output you're seeing. Thx > > let(:subtest) {MyModule.subtest_to_sym(subtest)} > > or > > before(:each) do > @subtest = MyModule.subtest_to_sym(subtest) > end > > Instead I have to avoid the @ or let examples, and use the more > explicit (verbose): > > MyModule.subtest_to_sym(subtest) > > using the let or before @ approaches both fail. > > Using puts within the code (for debugging purposes) I found that the > specs were only being exposed to the final value of the array, while I > expected (and have seen, or at least assumed from past passes) that > all 4 (or so) of the strings were being used to create unique methods > on the example group (one per iteration). > > > Is this something that should be: > > a. avoided, because it's crazy, and written differently > b, documented > c. investigated further > > I can provide a more complete example if helpful? > > Thanks, > Nick > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From nicholas.wieland at gmail.com Wed Jul 28 21:16:42 2010 From: nicholas.wieland at gmail.com (Nicholas Wieland) Date: Wed, 28 Jul 2010 18:16:42 -0700 Subject: [rspec-users] Testing subdomains In-Reply-To: <62529D5F-CC48-4E2D-8BF6-46AD8AFB764E@gmail.com> References: <62529D5F-CC48-4E2D-8BF6-46AD8AFB764E@gmail.com> Message-ID: <0A77CA19-052A-4162-A796-6A4EB2F4871F@gmail.com> On Jul 27, 2010, at 6:40 PM, Nicholas Wieland wrote: > Hi *, is someone using rspec 2 and rails 3 for testing subdomains ? How do I test for example in a route spec tis route ? > > match 'profile', :to => 'users#profile', :constraints => { :subdomain => /.+/ } it "routes /profile to UsersController#profile for slug" do { :get => "profile" }.should route_to( :controller => :users, :action => :profile, :permalink => 'test' ) end This fails with undefined method `subdomain' for # I'm not able to set the host, host! doesn't work, or I'm using it in the wrong way. Someone has any idea ? ngw From lists at ruby-forum.com Thu Jul 29 06:19:00 2010 From: lists at ruby-forum.com (Amit Jain) Date: Thu, 29 Jul 2010 12:19:00 +0200 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati Message-ID: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> Hello, I recently unpacked the latest rspec and rspec rails in my applicaiton. When I run my specs I get: $ rcov user_spec.rb config.gem: Unpacked gem CVS in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this. config.gem: Unpacked gem CVS in vendor/gems not in a versioned directory. Giving up. config.gem: Unpacked gem rmagick-2.13.1 in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this. /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- application (MissingSourceFile) from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in `require' from /home/Amit/Myworkspace/MyApplication/vendor/plugins/rspec_on_rails/lib/spec/rails.rb:3 from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in `require' from ./../spec_helper.rb:6 from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from ./user_spec.rb:1 from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511:in `load' from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 from /usr/bin/rcov:19:in `load' from /usr/bin/rcov:19 -- Posted via http://www.ruby-forum.com/. From lists at ruby-forum.com Thu Jul 29 06:24:01 2010 From: lists at ruby-forum.com (Amit Jain) Date: Thu, 29 Jul 2010 12:24:01 +0200 Subject: [rspec-users] `gem_original_require': no such file to load Message-ID: Hi All, I am getting such types of errors with rspec implementation. $ rcov user_spec.rb config.gem: Unpacked gem CVS in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this. config.gem: Unpacked gem CVS in vendor/gems not in a versioned directory. Giving up. config.gem: Unpacked gem rmagick-2.13.1 in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this. /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- application (MissingSourceFile) from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in `require' from /home/Amit/Myworkspace/MyApplication/vendor/plugins/rspec_on_rails/lib/spec/rails.rb:3 from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in `require' from ./../spec_helper.rb:6 from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from ./user_spec.rb:1 from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511:in `load' from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 from /usr/bin/rcov:19:in `load' from /usr/bin/rcov:19 Please help me how can i resolved it. Thanks Amit Jain -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Thu Jul 29 07:14:33 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 29 Jul 2010 06:14:33 -0500 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> Message-ID: On Jul 29, 2010, at 5:19 AM, Amit Jain wrote: > Hello, > I recently unpacked the latest rspec and rspec rails in my > applicaiton. How did you unpack them (what command did you use)? > When I run my specs I get: > > $ rcov user_spec.rb Where are you typing this command? What happens when you type "rake spec" from the project root? > config.gem: Unpacked gem CVS in vendor/gems has no specification file. This error suggests that you unpacked the gem using "gem unpack" instead of "rake gems:unpack". > Run 'rake gems:refresh_specs' to fix this. > config.gem: Unpacked gem CVS in vendor/gems not in a versioned > directory. Giving up. And this one suggests that you may have put a CVS plugin directly in the gems folder. Rails wants you to put plugins in vendor/plugins, and use "rake gems:unpack" to install gems in vendor/gems. > config.gem: Unpacked gem rmagick-2.13.1 in vendor/gems has no > specification file. Run 'rake gems:refresh_specs' to fix this. > /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `gem_original_require': no such file to load -- application > (MissingSourceFile) > from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `require' > from > /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in > `require' > from > /home/Amit/Myworkspace/MyApplication/vendor/plugins/rspec_on_rails/lib/spec/rails.rb:3 What version of rails are you using? rspec_on_rails was replaced by rspec-rails nearly two years ago, when rails was at 2.1.x. If you're using any version of rails later than 2.1, you should be using the rspec-rails gem. > from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `gem_original_require' > from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `require' > from > /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in > `require' > from ./../spec_helper.rb:6 > from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `gem_original_require' > from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `require' > from ./user_spec.rb:1 > from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511:in `load' > from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 > from /usr/bin/rcov:19:in `load' > from /usr/bin/rcov:19 From lists at ruby-forum.com Thu Jul 29 07:37:26 2010 From: lists at ruby-forum.com (Amit Jain) Date: Thu, 29 Jul 2010 13:37:26 +0200 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> Message-ID: <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> David Chelimsky wrote: > On Jul 29, 2010, at 5:19 AM, Amit Jain wrote: >> Hello, >> I recently unpacked the latest rspec and rspec rails in my >> applicaiton. > > How did you unpack them (what command did you use)? I just install rspec gem through the commands: root# gem install rspec root# gem install rcov and ~/mygreatapp/ $ ./script/plugin install svn://rubyforge.org/var/svn/rspec/tags/REL_X_Y_Z/vendor/rspec_on_rails/vendor/plugins/rspec but it's not work ~/mygreatapp/ $ ./script/generate rspec and then ./script/generate rspec_model User > >> When I run my specs I get: >> >> $ rcov user_spec.rb > > Where are you typing this command? What happens when you type "rake > spec" from the project root? > I run that command in /spec/models directory /spec/models $ rcov user_spec.rb >> config.gem: Unpacked gem CVS in vendor/gems has no specification file. > > This error suggests that you unpacked the gem using "gem unpack" instead > of "rake gems:unpack". > >> Run 'rake gems:refresh_specs' to fix this. >> config.gem: Unpacked gem CVS in vendor/gems not in a versioned >> directory. Giving up. > > And this one suggests that you may have put a CVS plugin directly in the > gems folder. Rails wants you to put plugins in vendor/plugins, and use > "rake gems:unpack" to install gems in vendor/gems. > >> from >> /home/Amit/Myworkspace/MyApplication/vendor/plugins/rspec_on_rails/lib/spec/rails.rb:3 > > What version of rails are you using? rspec_on_rails was replaced by > rspec-rails nearly two years ago, when rails was at 2.1.x. If you're > using any version of rails later than 2.1, you should be using the > rspec-rails gem. I am using Rails 2.3.4. -- Posted via http://www.ruby-forum.com/. From lists at ruby-forum.com Thu Jul 29 08:24:52 2010 From: lists at ruby-forum.com (Amit Jain) Date: Thu, 29 Jul 2010 14:24:52 +0200 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> Message-ID: <871e6b98c7367c1fa9aa5f562c59737a@ruby-forum.com> Amit Jain wrote: > David Chelimsky wrote: >> On Jul 29, 2010, at 5:19 AM, Amit Jain wrote: >>> Hello, >>> I recently unpacked the latest rspec and rspec rails in my >>> applicaiton. >> >> How did you unpack them (what command did you use)? > I just install rspec gem through the commands: > root# gem install rspec > root# gem install rcov > > and > > ~/mygreatapp/ $ ./script/plugin install > svn://rubyforge.org/var/svn/rspec/tags/REL_X_Y_Z/vendor/rspec_on_rails/vendor/plugins/rspec > > but it's not work > > ~/mygreatapp/ $ ./script/generate rspec > and then > ./script/generate rspec_model User > >> >>> When I run my specs I get: >>> >>> $ rcov user_spec.rb >> >> Where are you typing this command? What happens when you type "rake >> spec" from the project root? >> I run that command in /spec/models directory > > /spec/models $ rcov user_spec.rb > >>> config.gem: Unpacked gem CVS in vendor/gems has no specification file. >> >> This error suggests that you unpacked the gem using "gem unpack" instead >> of "rake gems:unpack". >> >>> Run 'rake gems:refresh_specs' to fix this. >>> config.gem: Unpacked gem CVS in vendor/gems not in a versioned >>> directory. Giving up. >> >> And this one suggests that you may have put a CVS plugin directly in the >> gems folder. Rails wants you to put plugins in vendor/plugins, and use >> "rake gems:unpack" to install gems in vendor/gems. >> >>> from >>> /home/Amit/Myworkspace/MyApplication/vendor/plugins/rspec_on_rails/lib/spec/rails.rb:3 >> >> What version of rails are you using? rspec_on_rails was replaced by >> rspec-rails nearly two years ago, when rails was at 2.1.x. If you're >> using any version of rails later than 2.1, you should be using the >> rspec-rails gem. > > I am using Rails 2.3.4. Hi Devid, Thanks for answer but i am still getting same problem. i am sending one another error: i run this command [root at localhost gems]# rake gems:unpack rspec_rails and get error: config.gem: Unpacked gem CVS in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this. config.gem: Unpacked gem CVS in vendor/gems not in a versioned directory. Giving up. config.gem: Unpacked gem rmagick-2.13.1 in vendor/gems has no specification file. Run 'rake gems:refresh_specs' to fix this. rake aborted! no such file to load -- spec/translator please help me............ -- Posted via http://www.ruby-forum.com/. From lists at ruby-forum.com Thu Jul 29 08:46:50 2010 From: lists at ruby-forum.com (Zhenning Guan) Date: Thu, 29 Jul 2010 14:46:50 +0200 Subject: [rspec-users] should_receive break the method chain? Message-ID: <9eb84a0f70288b573fd21819da9f38f5@ruby-forum.com> class A def process @b.calculate end end it 'should change b calculate value' do @b.should_receive(:calculate) @a.process @b.calculae_value.should == 'after_calculae' end it will fail, if I comment out #@b.should_receive(:calculate), the test pass, or if comment out #@b.calculae_value.should == 'after_calculae', also pass. so my colleague said maybe should_receive break the mehod chain and return. thing is really going this way? -- Posted via http://www.ruby-forum.com/. From mislav.marohnic at gmail.com Tue Jul 27 02:45:42 2010 From: mislav.marohnic at gmail.com (=?UTF-8?Q?Mislav_Marohni=C4=87?=) Date: Tue, 27 Jul 2010 08:45:42 +0200 Subject: [rspec-users] Gem post-install messages Message-ID: When you install the rspec-rails stack, the rspec gem post-install messages take more than 60 lines in total. Most of those messages are something uninformative like "thank you for installing the rspec-blah". Um, OK. You're welcome, I guess? http://pastie.org/1061716 The rspec-rails message is way too long, too. It should link to its web page with upgrade instructions for Rails apps. But looking at the rspec-rails GitHub project, I can't find the same instructions in the Readme, Upgrade.markdown or the wiki. So the post-install message for the gem contains the most useful upgrade documentation? That's no good. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ticktricktrack at gmail.com Tue Jul 27 08:29:23 2010 From: ticktricktrack at gmail.com (Rainer Kuhn) Date: Tue, 27 Jul 2010 05:29:23 -0700 (PDT) Subject: [rspec-users] proposition: warn on rake spec - group :test Message-ID: Consider putting out some information on rake spec, when rspec ist only defined in the :test group. This just cost me an hour until I read the blog post explaining it. Thing is, rake spec doesn't show on "rake -T" but it runs fine, just not doing anything. One line of output, like: "Either use RAILS_ENV=test or put 'gem rspec' in the :development group" would be nice Thanks Ray From dchelimsky at gmail.com Thu Jul 29 09:18:12 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 29 Jul 2010 08:18:12 -0500 Subject: [rspec-users] Gem post-install messages In-Reply-To: References: Message-ID: <4B80E6B3-4EAD-4221-9E27-B8FD8B024374@gmail.com> On Jul 27, 2010, at 1:45 AM, Mislav Marohni? wrote: > When you install the rspec-rails stack, the rspec gem post-install messages take more than 60 lines in total. Most of those messages are something uninformative like "thank you for installing the rspec-blah". Um, OK. You're welcome, I guess? > > http://pastie.org/1061716 > > The rspec-rails message is way too long, too. It should link to its web page with upgrade instructions for Rails apps. But looking at the rspec-rails GitHub project, I can't find the same instructions in the Readme, Upgrade.markdown or the wiki. So the post-install message for the gem contains the most useful upgrade documentation? That's no good. All good advice. Please report this last bit to http://github.com/rspec/rspec-rails/issues so it stays on the radar. I'll remove the "thank you" from the other ones now. Cheers, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From dchelimsky at gmail.com Thu Jul 29 09:29:27 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 29 Jul 2010 08:29:27 -0500 Subject: [rspec-users] proposition: warn on rake spec - group :test In-Reply-To: References: Message-ID: On Jul 27, 2010, at 7:29 AM, Rainer Kuhn wrote: > Consider putting out some information on rake spec, when rspec ist > only defined in the :test group. > This just cost me an hour until I read the blog post explaining it. > > Thing is, rake spec doesn't show on "rake -T" but it runs fine, just > not doing anything. > One line of output, like: > > "Either use RAILS_ENV=test or put 'gem rspec' in the :development > group" > > would be nice RSpec can't do anything if it's not loaded, which is the case when you run rake -T without rspec-rails in the :development group. I realize that this is new, but this is the way Rails-3 is supposed to work and we're all going to be learning how Gemfiles work for a while. Note that when you generate a new Rails-3 app (as of the release candidate), the generated Gemfile says this: # Bundle gems for the local environment. Make sure to # put test-only gems in this group so their generators # and rake tasks are available in development mode: # group :development, :test do # gem 'webrat' # end HTH, David From dchelimsky at gmail.com Thu Jul 29 09:31:48 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 29 Jul 2010 08:31:48 -0500 Subject: [rspec-users] should_receive break the method chain? In-Reply-To: <9eb84a0f70288b573fd21819da9f38f5@ruby-forum.com> References: <9eb84a0f70288b573fd21819da9f38f5@ruby-forum.com> Message-ID: On Jul 29, 2010, at 7:46 AM, Zhenning Guan wrote: > class A > def process > @b.calculate > end > end > > > it 'should change b calculate value' do > @b.should_receive(:calculate) > @a.process > > @b.calculae_value.should == 'after_calculae' > end > > it will fail, if I comment out #@b.should_receive(:calculate), the test > pass, > or if comment out #@b.calculae_value.should == 'after_calculae', also > pass. > > so my colleague said maybe should_receive break the mehod chain and > return. > thing is really going this way? Your colleague is correct. Any time you use object.stub(:method) or object.should_receive(:method) on a real object, the method is replaced by the mock framework. This is true with all of the popular ruby mock/test double frameworks. The one way to get around that is to use RR's[1] proxy. HTH, David [1] http://github.com/btakita/rr From lists at ruby-forum.com Thu Jul 29 09:37:40 2010 From: lists at ruby-forum.com (Anderson Leite) Date: Thu, 29 Jul 2010 15:37:40 +0200 Subject: [rspec-users] Testing controller and action with parameters Message-ID: <9773f56a6f7b52ed6c911201d450bd4d@ruby-forum.com> I have an action and I am testing it like this: The action: ========== def create @event = Evento.new(params[:event]) @event.aproved = false if @event.save redirect_to :action => "index" else render :action => "new" end end The RSpec test: ============== before do @event = mock_model(Event) Event.stub!(:new).and_return(@event) @event.stub!(:aproved=).and_return(false) @event.stub!(:save).and_return(true) end it "should register some event and keep it not aproved" do Event.should_receive(:new).once @event.should_receive(:aproved=).once @event.should_receive(:save).once get "create" response.should redirect_to :action => 'index' end It seems to be working for me and the test is passing, by I think this test is still ugly or probabily can be improved. How do you make tests like this? -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Thu Jul 29 09:59:41 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 29 Jul 2010 08:59:41 -0500 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> Message-ID: <3ABDC4AE-4FA2-4646-99C1-6D260A2817C3@gmail.com> On Jul 29, 2010, at 6:37 AM, Amit Jain wrote: > David Chelimsky wrote: >> On Jul 29, 2010, at 5:19 AM, Amit Jain wrote: >>> Hello, >>> I recently unpacked the latest rspec and rspec rails in my >>> applicaiton. >> >> How did you unpack them (what command did you use)? > I just install rspec gem through the commands: > root# gem install rspec > root# gem install rcov > > and > > ~/mygreatapp/ $ ./script/plugin install > svn://rubyforge.org/var/svn/rspec/tags/REL_X_Y_Z/vendor/rspec_on_rails/vendor/plugins/rspec rspec_on_rails is 2 years old and works with 2 year old versions of rails. Please do this: 1. delete all rspec plugins from vendor/plugins 2. configure the rspec-rails gem in config/environment.rb: config.gem "rspec-rails", :version => ">= 1.3.2" 3. rake gems:install 4. rake gems:unpack The problem you're having with CVS in vendor/gems is that you installed it using some means other than what is recommended by Rails, which is to use "rake gems:unpack". Please remove that and any other gems that you didn't install with "rake gems:unpack" from your vendor/gems directory, configure them config/environment.rb, and re-install them with "rake gems:unpack". If you continue to have trouble with this, please consult the ruby-on-rails documentation and/or mailing lists, as your issues are gem/plugin installation issues, not RSpec issues. HTH, David > > but it's not work > > ~/mygreatapp/ $ ./script/generate rspec > and then > ./script/generate rspec_model User > >> >>> When I run my specs I get: >>> >>> $ rcov user_spec.rb >> >> Where are you typing this command? What happens when you type "rake >> spec" from the project root? >> I run that command in /spec/models directory > > /spec/models $ rcov user_spec.rb > >>> config.gem: Unpacked gem CVS in vendor/gems has no specification file. >> >> This error suggests that you unpacked the gem using "gem unpack" instead >> of "rake gems:unpack". >> >>> Run 'rake gems:refresh_specs' to fix this. >>> config.gem: Unpacked gem CVS in vendor/gems not in a versioned >>> directory. Giving up. >> >> And this one suggests that you may have put a CVS plugin directly in the >> gems folder. Rails wants you to put plugins in vendor/plugins, and use >> "rake gems:unpack" to install gems in vendor/gems. >> >>> from >>> /home/Amit/Myworkspace/MyApplication/vendor/plugins/rspec_on_rails/lib/spec/rails.rb:3 >> >> What version of rails are you using? rspec_on_rails was replaced by >> rspec-rails nearly two years ago, when rails was at 2.1.x. If you're >> using any version of rails later than 2.1, you should be using the >> rspec-rails gem. > > I am using Rails 2.3.4. > -- > 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 Jul 29 10:06:22 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Thu, 29 Jul 2010 09:06:22 -0500 Subject: [rspec-users] Testing controller and action with parameters In-Reply-To: <9773f56a6f7b52ed6c911201d450bd4d@ruby-forum.com> References: <9773f56a6f7b52ed6c911201d450bd4d@ruby-forum.com> Message-ID: <0F22B81A-CCB8-49C4-B6CF-35C6D1FA9865@gmail.com> On Jul 29, 2010, at 8:37 AM, Anderson Leite wrote: > I have an action and I am testing it like this: > > The action: > ========== > def create > @event = Evento.new(params[:event]) > @event.aproved = false > if @event.save > redirect_to :action => "index" > else > render :action => "new" > end > end > > > The RSpec test: > ============== > > before do > @event = mock_model(Event) > Event.stub!(:new).and_return(@event) Use stub instead of stub! (which will eventually be deprecated) > @event.stub!(:aproved=).and_return(false) > @event.stub!(:save).and_return(true) You can add the method stubs to the mock_model declaration: @event = mock_model(Event, :approved= => false, :save => true) > end > > it "should register some event and keep it not aproved" do The word "and" in an example's name suggests too many things are being spec'd in one example. I'd split these out into "registers the event" and "leaves the event un-approved" HTH, David > Event.should_receive(:new).once > @event.should_receive(:aproved=).once > @event.should_receive(:save).once > get "create" > response.should redirect_to :action => 'index' > end > > > It seems to be working for me and the test is passing, by I think this > test is still ugly or probabily can be improved. > > How do you make tests like this? From lists at ruby-forum.com Fri Jul 30 03:03:29 2010 From: lists at ruby-forum.com (Amit Jain) Date: Fri, 30 Jul 2010 09:03:29 +0200 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <3ABDC4AE-4FA2-4646-99C1-6D260A2817C3@gmail.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> <3ABDC4AE-4FA2-4646-99C1-6D260A2817C3@gmail.com> Message-ID: <4776ca54fb899a21d7084873ced423a3@ruby-forum.com> David Chelimsky wrote: > On Jul 29, 2010, at 6:37 AM, Amit Jain wrote: > >> >> and >> >> ~/mygreatapp/ $ ./script/plugin install >> svn://rubyforge.org/var/svn/rspec/tags/REL_X_Y_Z/vendor/rspec_on_rails/vendor/plugins/rspec > > rspec_on_rails is 2 years old and works with 2 year old versions of > rails. Please do this: > > 1. delete all rspec plugins from vendor/plugins > 2. configure the rspec-rails gem in config/environment.rb: > > config.gem "rspec-rails", :version => ">= 1.3.2" > > 3. rake gems:install > 4. rake gems:unpack > > The problem you're having with CVS in vendor/gems is that you installed > it using some means other than what is recommended by Rails, which is to > use "rake gems:unpack". Please remove that and any other gems that you > didn't install with "rake gems:unpack" from your vendor/gems directory, > configure them config/environment.rb, and re-install them with "rake > gems:unpack". > > If you continue to have trouble with this, please consult the > ruby-on-rails documentation and/or mailing lists, as your issues are > gem/plugin installation issues, not RSpec issues. > > HTH, > David I am getting some different error message: $rcov user_spec.rb /home/Amit/Myworkspace/MyApplication/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:119:Warning: Gem::Dependency#version_requirements is deprecated and will be removed on or after August 2010. Use #requirement /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:440:in `load_missing_constant': uninitialized constant Rails::Railtie (NameError) from /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:80:in `const_missing' from /home/Amit/Myworkspace/MyApplication/vendor/gems/rspec-rails-2.0.0.beta.19/lib/rspec-rails.rb:3 from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in `require' from /home/Amit/Myworkspace/MyApplication/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:208:in `load' from /home/Amit/Myworkspace/MyApplication/config/../vendor/rails/railties/lib/initializer.rb:307:in `load_gems' from /home/Amit/Myworkspace/MyApplication/config/../vendor/rails/railties/lib/initializer.rb:307:in `each' ... 11 levels... from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511:in `load' from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 from /usr/bin/rcov:19:in `load' from /usr/bin/rcov:19 Please help me. Thanks Amit Jain -- Posted via http://www.ruby-forum.com/. From ticktricktrack at gmail.com Fri Jul 30 04:09:42 2010 From: ticktricktrack at gmail.com (Rainer Kuhn) Date: Fri, 30 Jul 2010 01:09:42 -0700 (PDT) Subject: [rspec-users] proposition: warn on rake spec - group :test In-Reply-To: References: Message-ID: That's not entirely true, there is a diffence between lot loaded and not defined, let me show you: This is without rspec in the dev group, so it does not show in rake - T: ~/work/myproject$ rake spec (in /Users/rainerkuhn/work/myproject) ~/work/myproject$ rake IdontExist (in /Users/rainerkuhn/work/myproject) rake aborted! Don't know how to build task 'IdontExist' (See full trace by running task with --trace) ~/work/myproject$ On Jul 29, 3:29?pm, David Chelimsky wrote: > On Jul 27, 2010, at 7:29 AM, Rainer Kuhn wrote: > > > Consider putting out some information on rake spec, when rspec ist > > only defined in the :test group. > > This just cost me an hour until I read the blog post explaining it. > > > Thing is, rake spec doesn't show on "rake -T" but it runs fine, just > > not doing anything. > > One line of output, like: > > > "Either use RAILS_ENV=test or put 'gem rspec' in the :development > > group" > > > would be nice > > RSpec can't do anything if it's not loaded, which is the case when you run rake -T without rspec-rails in the :development group. I realize that this is new, but this is the way Rails-3 is supposed to work and we're all going to be learning how Gemfiles work for a while. Note that when you generate a new Rails-3 app (as of the release candidate), the generated Gemfile says this: > > # Bundle gems for the local environment. Make sure to > # put test-only gems in this group so their generators > # and rake tasks are available in development mode: > # group :development, :test do > # ? gem 'webrat' > # end > > HTH, > David > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From ashley.moran at patchspace.co.uk Fri Jul 30 06:13:13 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Fri, 30 Jul 2010 11:13:13 +0100 Subject: [rspec-users] Evaluating shared example customisation block before shared block Message-ID: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> Hi I finally looked into why this is not currently possibly in RSpec 2 (beta 19): shared_examples_for "Etymology" do describe "The etymology of foo" do it "is followed by #{after_foo}" do # ... end end end describe "foo", focus: true do it_should_behave_like "Etymology" do def self.after_foo "bar" end end end It's because of the current implementation of ExampleGroup.define_shared_group_method, which evaluates the shared example block before the customisation block: shared_group = describe("#{report_label} \#{name}", &shared_block) shared_group.class_eval(&customization_block) if customization_block (This is behaviour I found surprising.) However, with a little more metaprogramming jiggery-pokery, you can have them evaluated in the other order: module RSpec module Core class ExampleGroup # ... def self.define_shared_group_method(new_name, report_label=nil) report_label = "it should behave like" unless report_label module_eval(<<-END_RUBY, __FILE__, __LINE__) def self.#{new_name}(name, &customization_block) shared_block = world.shared_example_groups[name] raise "Could not find shared example group named \#{name.inspect}" unless shared_block compound_block = lambda do |*args| module_eval &customization_block if customization_block module_eval &shared_block end shared_group = describe("#{report_label} \#{name}", &compound_block) shared_group end END_RUBY end # ... end end end Would this be a useful improvement to RSpec 2? Any opinions on the order of the block evaluation for shared examples? Cheers Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From martin.hawkins at gmail.com Fri Jul 30 06:53:26 2010 From: martin.hawkins at gmail.com (Martin Hawkins) Date: Fri, 30 Jul 2010 03:53:26 -0700 (PDT) Subject: [rspec-users] Newbie : How to spec params hash amendment Message-ID: <9bca94b8-b2eb-488a-b81b-8c04a56b5cbe@l14g2000yql.googlegroups.com> I am new to rspec and am finding it all a bit daunting at the moment. I'd like to be able to adopt a bdd approach to my development but I'm still at the stage of trying to get my head around rspec concepts so I'm committing the cardinal sin of coding first and then writing tests. I am using the following: Ruby v1.8.7 Rails v2.3.8 Authlogic v2.1.5 Cancan v1.2.0 rspec v1.3.0 rspec-rails v1.3.2 webrat v0.7.1 cucumber-rails v0.3.2 capybara v0.3.9 factory_girl v1.2.4 pickle v0.3.0 no_peeping_toms v1.1.0 email_spec v0.6.2 In spec_helper.rb, I have def current_user(stubs = {}) @current_user ||= mock_model(User, stubs) end def user_session(stubs = {}, user_stubs = {}) @current_user_session ||= mock_model(UserSession, {:user => current_user(user_stubs)}.merge(stubs)) end def login(session_stubs = {}, user_stubs = {}) UserSession.stub!(:find).and_return(user_session(session_stubs, user_stubs)) end def logout @user_session = nil end def login_as_admin login({}, {:role => 'admin'}) @current_user.stub(:role?).with(:admin).and_return(true) end In ability.rb (for cancan) def initialize(user) user ||= User.new # Guest user if user.role? :admin can [:index, :show, :new, :edit, :create, :update, :destroy], [User, CommonContents, Logo] else can [:show, :edit, :update], User cannot [:index, :show, :new, :edit, :create, :update, :destroy], [CommonContents, Logo] end end In UserController def create # New users can only be created by admins authorize! :create, User # When the user is first defined by admin, the password is not set # Create a random one to satisfy validation requirements, which the user changes when they first visit params[:user][:password] = random_password() params[:user][:password_confirmation] = params[:user][:password] @user = User.new(params[:user]) if @user.save redirect_to(@user, :notice => 'User was successfully created.') else @roles = User.const_get("ADMIN_CAN_CREATE") render :action => "new" end end I have a private method in ApplicationController as follows: def random_password(length = 10) alphanumerics = [('0'..'9'),('A'..'Z'),('a'..'z')].map {|range| range.to_a}.flatten (0...length).map { alphanumerics[Kernel.rand(alphanumerics.size)] }.join end My spec is currently describe "when authorised as admin" do describe "POST 'create'" do before(:each) do login_as_admin end after(:each) do logout end describe "with valid params" do it "should set password and password_confirmation to the same 10 digit value" do # ????? end end end end I have no idea how to approach 'rspec'ing the creation of the params[:user][:password] and :password_confirmation or the random_password method and would very much appreciate it if somebody could spare the time to suggest what I should be doing. From dchelimsky at gmail.com Fri Jul 30 07:17:15 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 06:17:15 -0500 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <4776ca54fb899a21d7084873ced423a3@ruby-forum.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> <3ABDC4AE-4FA2-4646-99C1-6D260A2817C3@gmail.com> <4776ca54fb899a21d7084873ced423a3@ruby-forum.com> Message-ID: <9465357E-4EBC-4BF1-BDDA-2DAB98F14EE7@gmail.com> On Jul 30, 2010, at 2:03 AM, Amit Jain wrote: > David Chelimsky wrote: >> On Jul 29, 2010, at 6:37 AM, Amit Jain wrote: >> >>> >>> and >>> >>> ~/mygreatapp/ $ ./script/plugin install >>> svn://rubyforge.org/var/svn/rspec/tags/REL_X_Y_Z/vendor/rspec_on_rails/vendor/plugins/rspec >> >> rspec_on_rails is 2 years old and works with 2 year old versions of >> rails. Please do this: >> >> 1. delete all rspec plugins from vendor/plugins >> 2. configure the rspec-rails gem in config/environment.rb: >> >> config.gem "rspec-rails", :version => ">= 1.3.2" >> >> 3. rake gems:install >> 4. rake gems:unpack >> >> The problem you're having with CVS in vendor/gems is that you installed >> it using some means other than what is recommended by Rails, which is to >> use "rake gems:unpack". Please remove that and any other gems that you >> didn't install with "rake gems:unpack" from your vendor/gems directory, >> configure them config/environment.rb, and re-install them with "rake >> gems:unpack". >> >> If you continue to have trouble with this, please consult the >> ruby-on-rails documentation and/or mailing lists, as your issues are >> gem/plugin installation issues, not RSpec issues. >> >> HTH, >> David > > I am getting some different error message: > > $rcov user_spec.rb > > /home/Amit/Myworkspace/MyApplication/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:119:Warning: > Gem::Dependency#version_requirements is deprecated and will be removed > on or after August 2010. Use #requirement > /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:440:in > `load_missing_constant': uninitialized constant Rails::Railtie > (NameError) > from > /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:80:in > `const_missing' > from > /home/Amit/Myworkspace/MyApplication/vendor/gems/rspec-rails-2.0.0.beta.19/lib/rspec-rails.rb:3 > from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `gem_original_require' > from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `require' > from > /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in > `require' > from > /home/Amit/Myworkspace/MyApplication/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:208:in > `load' > from > /home/Amit/Myworkspace/MyApplication/config/../vendor/rails/railties/lib/initializer.rb:307:in > `load_gems' > from > /home/Amit/Myworkspace/MyApplication/config/../vendor/rails/railties/lib/initializer.rb:307:in > `each' > ... 11 levels... > from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511:in `load' > from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 > from /usr/bin/rcov:19:in `load' > from /usr/bin/rcov:19 > Please help me. Please show me what you typed in your config/environment.rb to configure rspec-rails. From lists at ruby-forum.com Fri Jul 30 07:52:02 2010 From: lists at ruby-forum.com (Amit Jain) Date: Fri, 30 Jul 2010 13:52:02 +0200 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <9465357E-4EBC-4BF1-BDDA-2DAB98F14EE7@gmail.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> <3ABDC4AE-4FA2-4646-99C1-6D260A2817C3@gmail.com> <4776ca54fb899a21d7084873ced423a3@ruby-forum.com> <9465357E-4EBC-4BF1-BDDA-2DAB98F14EE7@gmail.com> Message-ID: <8d1fa1c6bd9dfbd57bcb77323b8790ac@ruby-forum.com> David Chelimsky wrote: > On Jul 30, 2010, at 2:03 AM, Amit Jain wrote: > >>> rails. Please do this: >>> it using some means other than what is recommended by Rails, which is to >>> David >> (NameError) >> /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in >> ... 11 levels... >> from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511:in `load' >> from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 >> from /usr/bin/rcov:19:in `load' >> from /usr/bin/rcov:19 >> Please help me. > > Please show me what you typed in your config/environment.rb to > configure rspec-rails. Hi , I configure the rspec-rails gem in config/environment.rb: config.gem "rspec-rails", :version => ">= 1.3.2" Thanks Amit -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Fri Jul 30 08:09:35 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 07:09:35 -0500 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <8d1fa1c6bd9dfbd57bcb77323b8790ac@ruby-forum.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> <3ABDC4AE-4FA2-4646-99C1-6D260A2817C3@gmail.com> <4776ca54fb899a21d7084873ced423a3@ruby-forum.com> <9465357E-4EBC-4BF1-BDDA-2DAB98F14EE7@gmail.com> <8d1fa1c6bd9dfbd57bcb77323b8790ac@ruby-forum.com> Message-ID: <6ED57A47-B4B1-4822-AFA3-D62CBE08FF46@gmail.com> On Jul 30, 2010, at 6:52 AM, Amit Jain wrote: > David Chelimsky wrote: >> On Jul 30, 2010, at 2:03 AM, Amit Jain wrote: >> >>>> rails. Please do this: >>>> it using some means other than what is recommended by Rails, which is to >>>> David >>> (NameError) >>> /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:158:in >>> ... 11 levels... >>> from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511:in `load' >>> from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 >>> from /usr/bin/rcov:19:in `load' >>> from /usr/bin/rcov:19 >>> Please help me. >> >> Please show me what you typed in your config/environment.rb to >> configure rspec-rails. > > Hi , > > I configure the rspec-rails gem in config/environment.rb: > > config.gem "rspec-rails", :version => ">= 1.3.2" OK - so the problem now is that you've got rspec-rails 2.0.0.beta installed and that satisfies the ">= 1.3.2" gem requirement, but it only works with Rails 3. Try changing that to this: config.gem "rspec-rails", :version => "~> 1.3.2" The "~>" matches any gem versions that begin with 1.3, so if you later upgrade to 1.3.3 it will still work, but it won't match 2.0.0.xxx. Also, try running with the "rake spec" command before using rcov, which adds complexity to the mix. > Thanks > Amit > -- > 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 Fri Jul 30 08:47:14 2010 From: lists at ruby-forum.com (Amit Jain) Date: Fri, 30 Jul 2010 14:47:14 +0200 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <6ED57A47-B4B1-4822-AFA3-D62CBE08FF46@gmail.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> <3ABDC4AE-4FA2-4646-99C1-6D260A2817C3@gmail.com> <4776ca54fb899a21d7084873ced423a3@ruby-forum.com> <9465357E-4EBC-4BF1-BDDA-2DAB98F14EE7@gmail.com> <8d1fa1c6bd9dfbd57bcb77323b8790ac@ruby-forum.com> <6ED57A47-B4B1-4822-AFA3-D62CBE08FF46@gmail.com> Message-ID: <4eb3f64cfddba368d5071cf3cfcfeb02@ruby-forum.com> David Chelimsky wrote: > On Jul 30, 2010, at 6:52 AM, Amit Jain wrote: > >>>> from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 >> >> config.gem "rspec-rails", :version => ">= 1.3.2" > > OK - so the problem now is that you've got rspec-rails 2.0.0.beta > installed and that satisfies the ">= 1.3.2" gem requirement, but it only > works with Rails 3. Try changing that to this: > > config.gem "rspec-rails", :version => "~> 1.3.2" > > The "~>" matches any gem versions that begin with 1.3, so if you later > upgrade to 1.3.3 it will still work, but it won't match 2.0.0.xxx. > > Also, try running with the "rake spec" command before using rcov, which > adds complexity to the mix. Hi After adding config.gem "rspec-rails", :version => "~> 1.3.2" line in config/environment.rb file. i am getting such type of error. [Amit at localhost MyApplication]$ ruby script/server => Booting WEBrick => Rails 2.3.4 application starting on http://0.0.0.0:3000 can't activate rspec-rails (= 2.0.0.beta.19, runtime) for [], already activated rspec-rails-1.3.2 for [] /usr/lib/ruby/site_ruby/1.8/rubygems.rb:230:in `activate' /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:35:in `require' /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:156:in `require' /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:521:in `new_constants_in /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:156:in `require' /home/Amit/Myworkspace/MyApplication/vendor/rails/railties/lib/commands/server.rb:84 /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' script/server:3 Missing these required gems: rspec-rails ~> 1.3.2 You're running: ruby 1.8.6.399 at /usr/bin/ruby rubygems 1.3.6 at /home/Amit/.gem/ruby/1.8, /usr/lib/ruby/gems/1.8 Run `rake gems:install` to install the missing gems. --------------------------------------------------------- I try $ rake gems:install but not install any thing and i also try [root at localhost MyApplication]# gem uninstall rspec-rails-1.3.2 ERROR: While executing gem ... (Gem::InstallError) cannot uninstall, check `gem list -d rspec-rails-1.3.2` [root at localhost MyApplication]# `gem list -d rspec-rails-1.3.2` [root at localhost MyApplication]# I don't know about this error and why it is coming. -- Posted via http://www.ruby-forum.com/. From dchelimsky at gmail.com Fri Jul 30 09:09:59 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 08:09:59 -0500 Subject: [rspec-users] proposition: warn on rake spec - group :test In-Reply-To: References: Message-ID: On Jul 30, 2010, at 3:09 AM, Rainer Kuhn wrote: > On Jul 29, 3:29 pm, David Chelimsky wrote: >> On Jul 27, 2010, at 7:29 AM, Rainer Kuhn wrote: >> >>> Consider putting out some information on rake spec, when rspec ist >>> only defined in the :test group. >>> This just cost me an hour until I read the blog post explaining it. >> >>> Thing is, rake spec doesn't show on "rake -T" but it runs fine, just >>> not doing anything. >>> One line of output, like: >> >>> "Either use RAILS_ENV=test or put 'gem rspec' in the :development >>> group" >> >>> would be nice >> >> RSpec can't do anything if it's not loaded, which is the case when you run rake -T without rspec-rails in the :development group. I realize that this is new, but this is the way Rails-3 is supposed to work and we're all going to be learning how Gemfiles work for a while. Note that when you generate a new Rails-3 app (as of the release candidate), the generated Gemfile says this: >> >> # Bundle gems for the local environment. Make sure to >> # put test-only gems in this group so their generators >> # and rake tasks are available in development mode: >> # group :development, :test do >> # gem 'webrat' >> # end > That's not entirely true, there is a diffence between lot loaded and > not defined, let me show you: > > This is without rspec in the dev group, so it does not show in rake -T: > > ~/work/myproject$ rake spec > (in /Users/rainerkuhn/work/myproject) > > ~/work/myproject$ rake IdontExist > (in /Users/rainerkuhn/work/myproject) > rake aborted! > Don't know how to build task 'IdontExist' > > (See full trace by running task with --trace) > ~/work/myproject$ Interesting. I see the same behaviour, but it's not what you think it is. Try "rake spec:models" and you'll get the "Don't know how to build" error. I added a "raise" statement to the top of the rspec.rake file (i.e. the first line - raises if the file is even loaded) and it raises if I include rspec in the :development group, but not in the :test group. I then pulled rspec completely out of the Gemfile and, lo and behold, still no error on "rake spec" - just does nothing. Doesn't solve this issue, but does verify that RSpec won't be able to solve it. It'll have to come from either users getting used to the idea of putting rspec-rails in the :development group, or a change to Rails. ps - I moved your response from the top to the bottom. Please post inline or at the bottom so readers can follow the thread: http://idallen.com/topposting.html. From dchelimsky at gmail.com Fri Jul 30 09:12:18 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 08:12:18 -0500 Subject: [rspec-users] how to fix 'rake gems:refresh_specs' gems has no specificati In-Reply-To: <4eb3f64cfddba368d5071cf3cfcfeb02@ruby-forum.com> References: <82cfaa7f9b7723b86a9dd37a4c0b2bb5@ruby-forum.com> <7ddb2c6e3a40379ebd7a3840068ddbf3@ruby-forum.com> <3ABDC4AE-4FA2-4646-99C1-6D260A2817C3@gmail.com> <4776ca54fb899a21d7084873ced423a3@ruby-forum.com> <9465357E-4EBC-4BF1-BDDA-2DAB98F14EE7@gmail.com> <8d1fa1c6bd9dfbd57bcb77323b8790ac@ruby-forum.com> <6ED57A47-B4B1-4822-AFA3-D62CBE08FF46@gmail.com> <4eb3f64cfddba368d5071cf3cfcfeb02@ruby-forum.com> Message-ID: <171890AC-4C83-4D3E-BA2B-81B9314A3224@gmail.com> On Jul 30, 2010, at 7:47 AM, Amit Jain wrote: > David Chelimsky wrote: >> On Jul 30, 2010, at 6:52 AM, Amit Jain wrote: >> >>>>> from /usr/lib/ruby/gems/1.8/gems/rcov-0.9.8/bin/rcov:511 >>> >>> config.gem "rspec-rails", :version => ">= 1.3.2" >> >> OK - so the problem now is that you've got rspec-rails 2.0.0.beta >> installed and that satisfies the ">= 1.3.2" gem requirement, but it only >> works with Rails 3. Try changing that to this: >> >> config.gem "rspec-rails", :version => "~> 1.3.2" >> >> The "~>" matches any gem versions that begin with 1.3, so if you later >> upgrade to 1.3.3 it will still work, but it won't match 2.0.0.xxx. >> >> Also, try running with the "rake spec" command before using rcov, which >> adds complexity to the mix. > > Hi After adding > config.gem "rspec-rails", :version => "~> 1.3.2" > line in config/environment.rb file. i am getting such type of error. > > [Amit at localhost MyApplication]$ ruby script/server > > => Booting WEBrick > => Rails 2.3.4 application starting on http://0.0.0.0:3000 > can't activate rspec-rails (= 2.0.0.beta.19, runtime) for [], already > activated rspec-rails-1.3.2 for [] > /usr/lib/ruby/site_ruby/1.8/rubygems.rb:230:in `activate' > /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:35:in `require' > /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:156:in > `require' > /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:521:in > `new_constants_in > /home/Amit/Myworkspace/MyApplication/vendor/rails/activesupport/lib/active_support/dependencies.rb:156:in > `require' > /home/Amit/Myworkspace/MyApplication/vendor/rails/railties/lib/commands/server.rb:84 > /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in > `gem_original_require' > /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' > script/server:3 > Missing these required gems: > rspec-rails ~> 1.3.2 > > You're running: > ruby 1.8.6.399 at /usr/bin/ruby > rubygems 1.3.6 at /home/Amit/.gem/ruby/1.8, /usr/lib/ruby/gems/1.8 > > Run `rake gems:install` to install the missing gems. > --------------------------------------------------------- > > I try $ rake gems:install but not install any thing and i also try > > [root at localhost MyApplication]# gem uninstall rspec-rails-1.3.2 > ERROR: While executing gem ... (Gem::InstallError) > cannot uninstall, check `gem list -d rspec-rails-1.3.2` > [root at localhost MyApplication]# `gem list -d rspec-rails-1.3.2` > [root at localhost MyApplication]# > > I don't know about this error and why it is coming. Try this: gem install rspec-rails --version "1.3.2" From dchelimsky at gmail.com Fri Jul 30 10:03:41 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 09:03:41 -0500 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> Message-ID: <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> On Jul 30, 2010, at 5:13 AM, Ashley Moran wrote: > Hi > > I finally looked into why this is not currently possibly in RSpec 2 (beta 19): > > shared_examples_for "Etymology" do > describe "The etymology of foo" do > it "is followed by #{after_foo}" do > # ... > end > end > end > > describe "foo", focus: true do > it_should_behave_like "Etymology" do > def self.after_foo > "bar" > end > end > end > > It's because of the current implementation of ExampleGroup.define_shared_group_method, which evaluates the shared example block before the customisation block: > > shared_group = describe("#{report_label} \#{name}", &shared_block) > shared_group.class_eval(&customization_block) if customization_block > > (This is behaviour I found surprising.) > > However, with a little more metaprogramming jiggery-pokery, you can have them evaluated in the other order: > > module RSpec > module Core > class ExampleGroup > # ... > > def self.define_shared_group_method(new_name, report_label=nil) > report_label = "it should behave like" unless report_label > module_eval(<<-END_RUBY, __FILE__, __LINE__) > def self.#{new_name}(name, &customization_block) > shared_block = world.shared_example_groups[name] > raise "Could not find shared example group named \#{name.inspect}" unless shared_block > > compound_block = lambda do |*args| > module_eval &customization_block if customization_block > module_eval &shared_block > end > > shared_group = describe("#{report_label} \#{name}", &compound_block) > shared_group > end > END_RUBY > end > > # ... > end > end > end > Or ... def self.define_shared_group_method(new_name, report_label=nil) report_label = "it should behave like" unless report_label module_eval(<<-END_RUBY, __FILE__, __LINE__) def self.#{new_name}(name, &customization_block) shared_block = world.shared_example_groups[name] raise "Could not find shared example group named \#{name.inspect}" unless shared_block describe "#{report_label} \#{name}" do module_eval &customization_block if customization_block module_eval &shared_block end end END_RUBY end > Would this be a useful improvement to RSpec 2? Yes > Any opinions on the order of the block evaluation for shared examples Makes perfect sense to me. Wanna make a patch with an additional scenario in the cuke? > > Cheers > Ash > > -- > http://www.patchspace.co.uk/ > http://www.linkedin.com/in/ashleymoran > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Fri Jul 30 10:10:20 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 09:10:20 -0500 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> Message-ID: On Jul 30, 2010, at 9:03 AM, David Chelimsky wrote: > > On Jul 30, 2010, at 5:13 AM, Ashley Moran wrote: > >> Hi >> >> I finally looked into why this is not currently possibly in RSpec 2 (beta 19): >> >> shared_examples_for "Etymology" do >> describe "The etymology of foo" do >> it "is followed by #{after_foo}" do >> # ... >> end >> end >> end >> >> describe "foo", focus: true do >> it_should_behave_like "Etymology" do >> def self.after_foo >> "bar" >> end >> end >> end >> >> It's because of the current implementation of ExampleGroup.define_shared_group_method, which evaluates the shared example block before the customisation block: >> >> shared_group = describe("#{report_label} \#{name}", &shared_block) >> shared_group.class_eval(&customization_block) if customization_block >> >> (This is behaviour I found surprising.) >> >> However, with a little more metaprogramming jiggery-pokery, you can have them evaluated in the other order: >> >> module RSpec >> module Core >> class ExampleGroup >> # ... >> >> def self.define_shared_group_method(new_name, report_label=nil) >> report_label = "it should behave like" unless report_label >> module_eval(<<-END_RUBY, __FILE__, __LINE__) >> def self.#{new_name}(name, &customization_block) >> shared_block = world.shared_example_groups[name] >> raise "Could not find shared example group named \#{name.inspect}" unless shared_block >> >> compound_block = lambda do |*args| >> module_eval &customization_block if customization_block >> module_eval &shared_block >> end >> >> shared_group = describe("#{report_label} \#{name}", &compound_block) >> shared_group >> end >> END_RUBY >> end >> >> # ... >> end >> end >> end >> > > Or ... > > def self.define_shared_group_method(new_name, report_label=nil) > report_label = "it should behave like" unless report_label > module_eval(<<-END_RUBY, __FILE__, __LINE__) > def self.#{new_name}(name, &customization_block) > shared_block = world.shared_example_groups[name] > raise "Could not find shared example group named \#{name.inspect}" unless shared_block > > describe "#{report_label} \#{name}" do > module_eval &customization_block if customization_block > module_eval &shared_block > end > end > END_RUBY > end > >> Would this be a useful improvement to RSpec 2? > > Yes > >> Any opinions on the order of the block evaluation for shared examples > > Makes perfect sense to me. Wanna make a patch with an additional scenario in the cuke? Actually - maybe I spoke to soon. Ordering things this way would mean that you couldn't do this: shared_examples_for Enumerable do def enumerable raise "you must provide an enumerable method that returns the object which you're specifying should behave like Enumerable" end it "..." { .. } end Although, if you were going to do that, I guess you could do this: shared_examples_for Enumerable do unless defined?(:enumerable) raise "you must provide an enumerable method that returns the object which you're specifying should behave like Enumerable" end it "..." { .. } end Maybe that, or a DSL that wraps that, is the better way, so we can get the best of both worlds? shared_examples_for Enumerable do require_instance_method :foo, "gotta have foo instance method" require_class_method :foo, "gotta have foo class method" require_instance_variable "@foo", "gotta have an instance variable named @foo" it "..." { .. } end Thoughts? > >> >> Cheers >> Ash >> >> -- >> http://www.patchspace.co.uk/ >> http://www.linkedin.com/in/ashleymoran >> >> _______________________________________________ >> rspec-users mailing list >> rspec-users at rubyforge.org >> http://rubyforge.org/mailman/listinfo/rspec-users > From win at wincent.com Fri Jul 30 11:17:23 2010 From: win at wincent.com (Wincent Colaiuta) Date: Fri, 30 Jul 2010 17:17:23 +0200 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> Message-ID: El 30/07/2010, a las 16:10, David Chelimsky escribi?: > Actually - maybe I spoke to soon. Ordering things this way would mean that you couldn't do this: > > shared_examples_for Enumerable do > def enumerable > raise "you must provide an enumerable method that returns the object which you're specifying should behave like Enumerable" > end > it "..." { .. } > end > > Although, if you were going to do that, I guess you could do this: > > shared_examples_for Enumerable do > unless defined?(:enumerable) > raise "you must provide an enumerable method that returns the object which you're specifying should behave like Enumerable" > end > it "..." { .. } > end > > Maybe that, or a DSL that wraps that, is the better way, so we can get the best of both worlds? > > shared_examples_for Enumerable do > require_instance_method :foo, "gotta have foo instance method" > require_class_method :foo, "gotta have foo class method" > require_instance_variable "@foo", "gotta have an instance variable named @foo" > it "..." { .. } > end > > Thoughts? I think the DSL would probably be over-engineering. One of the purposes the DSL would fulfill is to alert the user if he/she forgets to provide some required support methods or variables, but you already get those alerts "for free" in the form of failing specs and NoMethodErrors etc, so I don't think that really justifies it. The other purpose of the DSL would be to explicitly list the "dependencies" of the shared example group to someone who's scanning it. Again, I'm not sure if it's really justified, given that a much simpler solution already exists: shared_examples_for Enumerable do # requires: # - instance method: foo # - class method: foo # - instance variable: @foo it "..." { ... } end (I'm a big fan of doing the simplest thing that could possibly work.) Cheers, Wincent From dchelimsky at gmail.com Fri Jul 30 11:47:55 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 10:47:55 -0500 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> Message-ID: <981CF404-7736-4591-BB76-E24AD27C33A4@gmail.com> On Jul 30, 2010, at 10:17 AM, Wincent Colaiuta wrote: > El 30/07/2010, a las 16:10, David Chelimsky escribi?: > >> Actually - maybe I spoke to soon. Ordering things this way would mean that you couldn't do this: >> >> shared_examples_for Enumerable do >> def enumerable >> raise "you must provide an enumerable method that returns the object which you're specifying should behave like Enumerable" >> end >> it "..." { .. } >> end >> >> Although, if you were going to do that, I guess you could do this: >> >> shared_examples_for Enumerable do >> unless defined?(:enumerable) >> raise "you must provide an enumerable method that returns the object which you're specifying should behave like Enumerable" >> end >> it "..." { .. } >> end >> >> Maybe that, or a DSL that wraps that, is the better way, so we can get the best of both worlds? >> >> shared_examples_for Enumerable do >> require_instance_method :foo, "gotta have foo instance method" >> require_class_method :foo, "gotta have foo class method" >> require_instance_variable "@foo", "gotta have an instance variable named @foo" >> it "..." { .. } >> end >> >> Thoughts? > > I think the DSL would probably be over-engineering. > > One of the purposes the DSL would fulfill is to alert the user if he/she forgets to provide some required support methods or variables, but you already get those alerts "for free" in the form of failing specs and NoMethodErrors etc, so I don't think that really justifies it. > > The other purpose of the DSL would be to explicitly list the "dependencies" of the shared example group to someone who's scanning it. Again, I'm not sure if it's really justified, given that a much simpler solution already exists: > > shared_examples_for Enumerable do > # requires: > # - instance method: foo > # - class method: foo > # - instance variable: @foo > > it "..." { ... } > end > > (I'm a big fan of doing the simplest thing that could possibly work.) That would only work if people read the docs :) The programatic approach would warn the user when they try to do something. I'm not sold on the DSL at this point, but I do like the idea of having a library help the developer do the right thing. If I provide spec extensions for a library (other than RSpec in this case) that include a shared group that "you can use to spec your foos to make sure they comply with this API" (or whatever), then this sort of thing can be very helpful. Make sense? > > Cheers, > Wincent > > > > _______________________________________________ > rspec-users mailing list > rspec-users at rubyforge.org > http://rubyforge.org/mailman/listinfo/rspec-users From ashley.moran at patchspace.co.uk Fri Jul 30 11:57:52 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Fri, 30 Jul 2010 16:57:52 +0100 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> Message-ID: <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> On Jul 30, 2010, at 3:10 pm, David Chelimsky wrote: > Maybe that, or a DSL that wraps that, is the better way, so we can get the best of both worlds? > > shared_examples_for Enumerable do > require_instance_method :foo, "gotta have foo instance method" > require_class_method :foo, "gotta have foo class method" > require_instance_variable "@foo", "gotta have an instance variable named @foo" > it "..." { .. } > end > > Thoughts? Actually, I *much* prefer this, as it makes it explicit what the host spec must provide in order to have the shared behaviour. (Wincent's email has just popped up so consider this a response to his message too.) I lean towards making things fail as early and explicitly as possible, as it reduces the total worldwide developer head-scratching time. InvalidSharedExampleUsageError("Must provide instance method :foo") or some such wins for me over NoMethodError("undefined method foo on <#Class ...>"). There should be no _requirement_ to use this DSL though, so the key would be to make sure it doesn't muddy the RSpec code. This is probably something that could be solved in code quicker than debate. It's a yak I'm happy to shave before getting back to my own project as it impacts what I'm working on ... want me to have a look at it this evening, David? I can fork rspec-core and play around with the idea. Regards Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From dchelimsky at gmail.com Fri Jul 30 12:00:51 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 11:00:51 -0500 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> Message-ID: <2A82081A-ED3E-423B-A068-3FB067F8C4B6@gmail.com> On Jul 30, 2010, at 10:57 AM, Ashley Moran wrote: > > On Jul 30, 2010, at 3:10 pm, David Chelimsky wrote: > >> Maybe that, or a DSL that wraps that, is the better way, so we can get the best of both worlds? >> >> shared_examples_for Enumerable do >> require_instance_method :foo, "gotta have foo instance method" >> require_class_method :foo, "gotta have foo class method" >> require_instance_variable "@foo", "gotta have an instance variable named @foo" >> it "..." { .. } >> end >> >> Thoughts? > > Actually, I *much* prefer this, as it makes it explicit what the host spec must provide in order to have the shared behaviour. (Wincent's email has just popped up so consider this a response to his message too.) I lean towards making things fail as early and explicitly as possible, as it reduces the total worldwide developer head-scratching time. InvalidSharedExampleUsageError("Must provide instance method :foo") or some such wins for me over NoMethodError("undefined method foo on <#Class ...>"). There should be no _requirement_ to use this DSL though, so the key would be to make sure it doesn't muddy the RSpec code. > > This is probably something that could be solved in code quicker than debate. It's a yak I'm happy to shave before getting back to my own project as it impacts what I'm working on ... want me to have a look at it this evening, David? I can fork rspec-core and play around with the idea. By all means. > Regards > Ash From ashley.moran at patchspace.co.uk Fri Jul 30 12:21:26 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Fri, 30 Jul 2010 17:21:26 +0100 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <981CF404-7736-4591-BB76-E24AD27C33A4@gmail.com> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> <981CF404-7736-4591-BB76-E24AD27C33A4@gmail.com> Message-ID: On Jul 30, 2010, at 4:47 pm, David Chelimsky wrote: > If I provide spec extensions for a library (other than RSpec in this case) that include a shared group that "you can use to spec your foos to make sure they comply with this API" (or whatever), then this sort of thing can be very helpful. Make sense? That's exactly what I want to do with the framework/library code I'm (slowly) extracting =) -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From nick.rutherford at gmail.com Fri Jul 30 17:00:46 2010 From: nick.rutherford at gmail.com (nruth) Date: Fri, 30 Jul 2010 14:00:46 -0700 (PDT) Subject: [rspec-users] rspec 1 - nested examples (in an each block) use the final block variable 4 times instead of each of the 4 once In-Reply-To: <815FC805-4DA8-46CB-853B-CC0BAE42B112@gmail.com> References: <815FC805-4DA8-46CB-853B-CC0BAE42B112@gmail.com> Message-ID: <9bf16ddf-7e76-4c0c-8f19-a2a11858f37b@g35g2000yqa.googlegroups.com> Hi David I think this was a case of idiot-end-user (or developer) on my part, sorry about that. I've produced a simple example here (and figured out what I was doing wrong). http://gist.github.com/501296 I don't think anything needs to change, though a wrapper?function (each + an inner describe) might help flag it as a possible pitfall. Thanks, Nick On Jul 29, 1:22?am, David Chelimsky wrote: > On Jul 28, 2010, at 5:42 PM, nruth wrote: > > > > > > > Please correct me if this is fixed in Rspec 2, but in Rspec 1 I have > > hit upon the following problem (at least thrice, this time it costing > > me several hours), code is the best example: > > > I have a practice examination system where each record is one of > > several "subtests" (think tagging rather than subclassing) which is > > part of a constant string array. I want to test each's behaviour > > indepently in my specs (since an earlier implementation used STI > > rather than tagging, and I want to test each kind of test follows the > > spec) > > > My specs use this approach in parts: > > > describe "#add_question_set_of_type" do > > ?MyModule::SUBTESTS.each do |subtest| > > > ? ?describe %Q("#{subtest}") do > > ? ?? specs using subtest > > ?end > > end > > > where SUBTESTS is a constant array of strings. > > > the problem is doing this breaks any blocks that look like > > Where are these blocks, in the outer or inner example group? Please provide a complete example, including everything I need to run and see the output you're seeing. > > Thx > > > > > > > > > ?let(:subtest) {MyModule.subtest_to_sym(subtest)} > > > or > > > ?before(:each) do > > ? ?@subtest = MyModule.subtest_to_sym(subtest) > > ?end > > > Instead I have to avoid the @ or let examples, and use the more > > explicit (verbose): > > > ?MyModule.subtest_to_sym(subtest) > > > using the let or before @ approaches both fail. > > > Using puts within the code (for debugging purposes) I found that the > > specs were only being exposed to the final value of the array, while I > > expected (and have seen, or at least assumed from past passes) that > > all 4 (or so) of the strings were being used to create unique methods > > on the example group (one per iteration). > > > Is this something that should be: > > > a. avoided, because it's crazy, and written differently > > b, documented > > c. investigated further > > > I can provide a more complete example if helpful? > > > Thanks, > > Nick > > _______________________________________________ > > rspec-users mailing list > > rspec-us... at rubyforge.org > >http://rubyforge.org/mailman/listinfo/rspec-users > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From ashley.moran at patchspace.co.uk Fri Jul 30 17:58:12 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Fri, 30 Jul 2010 22:58:12 +0100 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <2A82081A-ED3E-423B-A068-3FB067F8C4B6@gmail.com> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> <2A82081A-ED3E-423B-A068-3FB067F8C4B6@gmail.com> Message-ID: <81E33C70-68CD-4415-BC9E-23D0F2B6F0FB@patchspace.co.uk> On 30 Jul 2010, at 5:00 PM, David Chelimsky wrote: > By all means. I've started on that and filed a ticket[1]. One question I have, is I keep calling the Example Group that uses a shared block the "host group". Is there already a name for it? I never know what to use, and I'm not sure "host group" describes it accurately anyway. Cheers Ash [1] http://github.com/rspec/rspec-core/issues/issue/99 -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From ashley.moran at patchspace.co.uk Fri Jul 30 18:13:04 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Fri, 30 Jul 2010 23:13:04 +0100 Subject: [rspec-users] rspec 1 - nested examples (in an each block) use the final block variable 4 times instead of each of the 4 once In-Reply-To: <9bf16ddf-7e76-4c0c-8f19-a2a11858f37b@g35g2000yqa.googlegroups.com> References: <815FC805-4DA8-46CB-853B-CC0BAE42B112@gmail.com> <9bf16ddf-7e76-4c0c-8f19-a2a11858f37b@g35g2000yqa.googlegroups.com> Message-ID: <3B1DAA13-21E2-4022-AF9F-6BF5C791DFD7@patchspace.co.uk> On 30 Jul 2010, at 10:00 PM, nruth wrote: > http://gist.github.com/501296 > > I don't think anything needs to change, though a wrapper function > (each + an inner describe) might help flag it as a possible pitfall. Hi Nick I think the "before + ivar" pattern (below) is on its way out. At least, I consider it deprecated in my head: describe "before" do before(:each) { @foo = "bar" } before(:each) { @foo = "baz" } it "does this" do @foo.should eq "baz" end end But the new syntax does indeed let you redefine `let` blocks. describe "let" do let(:foo) { "bar" } let(:foo) { "baz" } it "does this (currently)" do foo.should eq "baz" end end Arguably, this is not the most desirable behaviour, as it leads to silent/confusing failures, as you've seen. Maybe it would be better if this raised an error? (Which is only an option with `let`, not with ivars.) Also, when combined with shared examples, this could conceivably be used to violate the Liskov Substitution Principle (if the LSP applies to specs). While Ruby as a language lets you redefine stuff at will, I'm not sure that's appropriate here. I can't imagine wanting to redefine a let, instead of factoring it out properly. Anyone got any thoughts on that? Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From myron.marston at gmail.com Fri Jul 30 19:56:35 2010 From: myron.marston at gmail.com (Myron Marston) Date: Fri, 30 Jul 2010 16:56:35 -0700 (PDT) Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <81E33C70-68CD-4415-BC9E-23D0F2B6F0FB@patchspace.co.uk> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> <2A82081A-ED3E-423B-A068-3FB067F8C4B6@gmail.com> <81E33C70-68CD-4415-BC9E-23D0F2B6F0FB@patchspace.co.uk> Message-ID: I may be the only one who finds this useful, but I think there's value in evaluating the customization block after the shared example group block. It allows the shared example group to provide a default implementation of a helper method, and then an instance of the shared behavior to override the helper method if appropriate. If you evaluate the customization block before the shared example group block, the default implementation wins out, and you have no way to override helper methods in an instance of a shared example group. On Jul 30, 2:58?pm, Ashley Moran wrote: > On 30 Jul 2010, at 5:00 PM, David Chelimsky wrote: > > > By all means. > > I've started on that and filed a ticket[1]. > > One question I have, is I keep calling the Example Group that uses a shared block the "host group". ?Is there already a name for it? ?I never know what to use, and I'm not sure "host group" describes it accurately anyway. > > Cheers > Ash > > [1]http://github.com/rspec/rspec-core/issues/issue/99 > > --http://www.patchspace.co.uk/http://www.linkedin.com/in/ashleymoran > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From dchelimsky at gmail.com Fri Jul 30 20:10:07 2010 From: dchelimsky at gmail.com (David Chelimsky) Date: Fri, 30 Jul 2010 19:10:07 -0500 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> <2A82081A-ED3E-423B-A068-3FB067F8C4B6@gmail.com> <81E33C70-68CD-4415-BC9E-23D0F2B6F0FB@patchspace.co.uk> Message-ID: <621BAF47-4CEC-4364-B706-6DFF7C9155A1@gmail.com> On Jul 30, 2010, at 6:56 PM, Myron Marston wrote: > On Jul 30, 2:58 pm, Ashley Moran > wrote: >> On 30 Jul 2010, at 5:00 PM, David Chelimsky wrote: >> >>> By all means. >> >> I've started on that and filed a ticket[1]. >> >> One question I have, is I keep calling the Example Group that uses a shared block the "host group". Is there already a name for it? I never know what to use, and I'm not sure "host group" describes it accurately anyway. >> >> Cheers >> Ash >> >> [1]http://github.com/rspec/rspec-core/issues/issue/99 >> >> --http://www.patchspace.co.uk/http://www.linkedin.com/in/ashleymoran > I may be the only one who finds this useful, but I think there's value > in evaluating the customization block after the shared example group > block. It allows the shared example group to provide a default > implementation of a helper method, and then an instance of the shared > behavior to override the helper method if appropriate. If you > evaluate the customization block before the shared example group > block, the default implementation wins out, and you have no way to > override helper methods in an instance of a shared example group. You can still get the same outcome, but you have to implement it in the group like this: unless defined?(:foo) def foo; "foo"; end end I think it's a good trade-off to put that burden on the group (and it's author) rather that the consumers of the group. From nick.rutherford at gmail.com Fri Jul 30 21:08:39 2010 From: nick.rutherford at gmail.com (nruth) Date: Fri, 30 Jul 2010 18:08:39 -0700 (PDT) Subject: [rspec-users] rspec 1 - nested examples (in an each block) use the final block variable 4 times instead of each of the 4 once In-Reply-To: <3B1DAA13-21E2-4022-AF9F-6BF5C791DFD7@patchspace.co.uk> References: <815FC805-4DA8-46CB-853B-CC0BAE42B112@gmail.com> <9bf16ddf-7e76-4c0c-8f19-a2a11858f37b@g35g2000yqa.googlegroups.com> <3B1DAA13-21E2-4022-AF9F-6BF5C791DFD7@patchspace.co.uk> Message-ID: <4d9de73c-43d5-456a-8c03-eb9b9686b771@m1g2000yqo.googlegroups.com> Hi Ash I've found let and before useful in different situations. I like let as a 'new feature' but am not sure it replaces, or is necessarily superior to, @vars in all cases for specs. If I want to set up a context to run some examples in (models created with machinist, associations, etc) then the before block makes it clear that that's the state the examples are running against, and the @vars give me a (quick and dirty?) hook to refer back to parts of that setup (e.g. associated models) in the spec examples. Of course, this can be done with let as well, but since they are lazy- evaluated you can end up with your examples running in the wrong context. For example: http://gist.github.com/501517 So after falling in love with let I've found sometimes it isn't worth the overhead & it's just quicker and tidyer to use before/@ ? I wonder whether in the end the only difference is the syntax highlighting, couple of extra lines of code or @ character, and perhaps the time / thought process in getting there. back to op briefly, I ended up with this approach for the specs instead: describe "#add_question_set_of_type('Abstract Reasoning')" do let(:subtest) {'Abstract Reasoning'} it_should_behave_like "adding a question set" end describe "#add_question_set_of_type('Decision Analysis')" do let(:subtest) {'Decision Analysis'} it_should_behave_like "adding a question set" end etc? perhaps not ideal if another test is added in later, and I wanted coverage of that too for free, but it avoided the immediate problem & is more clear what's going on. I certainly prefer let and subject to @vars for shared examples - again both work, but I find subject & lets provide a clear interface for the shared example groups which I felt was lacking when passing @variables around. Re: error / warning message, at the same scope (i.e. an accident, as in the op) then yes that could be quite useful for spotting mistakes. I'm not so sure about in different blocks though, it's probably intentional there (different context). Re: redefining vs refactoring - I like what you're saying (reminds me of dry vs non-dry specs, and I find myself refactoring a lot of my old spaghetti specs lately), but wonder if there are (edge) cases where it's useful or necessary. Maybe there's some discussion dating back to when the feature was added. It may be stylistic though, rather than enforceable? Re: LSP, food for thought, nothing to add at present unfortunately. Not sure what angle you're approaching shared examples from with that though, do you mean redefining lets inside of the shared example groups, or something else? Cheers, Nick On Jul 30, 11:13?pm, Ashley Moran wrote: > On 30 Jul 2010, at 10:00 PM, nruth wrote: > > >http://gist.github.com/501296 > > > I don't think anything needs to change, though a wrapper function > > (each + an inner describe) might help flag it as a possible pitfall. > > Hi Nick > > I think the "before + ivar" pattern (below) is on its way out. ?At least, I consider it deprecated in my head: > > ? describe "before" do > ? ? before(:each) { @foo = "bar" } > ? ? before(:each) { @foo = "baz" } > > ? ? it "does this" do > ? ? ? @foo.should eq "baz" > ? ? end > ? end > > But the new syntax does indeed let you redefine `let` blocks. > > ? describe "let" do > ? ? let(:foo) { "bar" } > ? ? let(:foo) { "baz" } > > ? ? it "does this (currently)" do > ? ? ? foo.should eq "baz" > ? ? end > ? end > > Arguably, this is not the most desirable behaviour, as it leads to silent/confusing failures, as you've seen. ?Maybe it would be better if this raised an error? ?(Which is only an option with `let`, not with ivars.) > > Also, when combined with shared examples, this could conceivably be used to violate the Liskov Substitution Principle (if the LSP applies to specs). ?While Ruby as a language lets you redefine stuff at will, I'm not sure that's appropriate here. ?I can't imagine wanting to redefine a let, instead of factoring it out properly. ?Anyone got any thoughts on that? > > Ash > > --http://www.patchspace.co.uk/http://www.linkedin.com/in/ashleymoran > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From ashley.moran at patchspace.co.uk Sat Jul 31 03:48:01 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sat, 31 Jul 2010 08:48:01 +0100 Subject: [rspec-users] rspec 1 - nested examples (in an each block) use the final block variable 4 times instead of each of the 4 once In-Reply-To: <4d9de73c-43d5-456a-8c03-eb9b9686b771@m1g2000yqo.googlegroups.com> References: <815FC805-4DA8-46CB-853B-CC0BAE42B112@gmail.com> <9bf16ddf-7e76-4c0c-8f19-a2a11858f37b@g35g2000yqa.googlegroups.com> <3B1DAA13-21E2-4022-AF9F-6BF5C791DFD7@patchspace.co.uk> <4d9de73c-43d5-456a-8c03-eb9b9686b771@m1g2000yqo.googlegroups.com> Message-ID: <887B44ED-E645-441D-A2A4-E9C4E1435B48@patchspace.co.uk> On 31 Jul 2010, at 2:08 AM, nruth wrote: > If I want to set up a context to run some examples in (models created > with machinist, associations, etc) then the before block makes it > clear that that's the state the examples are running against, and the > @vars give me a (quick and dirty?) hook to refer back to parts of that > setup (e.g. associated models) in the spec examples. > > Of course, this can be done with let as well, but since they are lazy- > evaluated you can end up with your examples running in the wrong > context. For example: http://gist.github.com/501517 Hi Nick I've been bitten by that too :) However, RSpec 2 comes to the rescue with `let!`, which evaluates the block immediately, so you don't have to call the method to get it evaluated. It's interesting though, I'll have to sit down some time and think through what the semantics of `before`, `let` and `let!` mean to me... > back to op briefly, I ended up with this approach for the specs > instead: > > describe "#add_question_set_of_type('Abstract Reasoning')" do > let(:subtest) {'Abstract Reasoning'} > it_should_behave_like "adding a question set" > end > > describe "#add_question_set_of_type('Decision Analysis')" do > let(:subtest) {'Decision Analysis'} > it_should_behave_like "adding a question set" > end > > etc? > > perhaps not ideal if another test is added in later, and I wanted > coverage of that too for free, but it avoided the immediate problem & > is more clear what's going on. Hmm, without seeing the rest of your code it's hard to say, but this looks like a case of Control Couple. Is there a case statement inside? If not is there any reason not to have methods #add_abstract_reasoning_question_set, #add_decision_analysis_question_set? If you're not branching on the parameter, how does the different behaviour come about? > I certainly prefer let and subject to @vars for shared examples - > again both work, but I find subject & lets provide a clear interface > for the shared example groups which I felt was lacking when passing > @variables around. I agree. I'm going to see if I can tighten this up today with a DSL to explicitly name the requirements of a shared example. (See the thread "Evaluating shared example customisation block before shared block".) > Re: error / warning message, at the same scope (i.e. an accident, as > in the op) then yes that could be quite useful for spotting mistakes. > I'm not so sure about in different blocks though, it's probably > intentional there (different context). > > Re: redefining vs refactoring - I like what you're saying (reminds me > of dry vs non-dry specs, and I find myself refactoring a lot of my old > spaghetti specs lately), but wonder if there are (edge) cases where > it's useful or necessary. Maybe there's some discussion dating back to > when the feature was added. It may be stylistic though, rather than > enforceable? > > Re: LSP, food for thought, nothing to add at present unfortunately. > Not sure what angle you're approaching shared examples from with that > though, do you mean redefining lets inside of the shared example > groups, or something else? Redefining lets anywhere actually. The case for doing it within an example group is probably stronger, as you wrote (or can manage) all the examples yourself. I guess if RSpec raised an error when a shared example accidentally redefines something from the host group, that would be noise, and force you to change your own code unnecessarily. Hopefully, if shared examples can say "I require these things to be set up", that issues won't arise. We'll see :) Ash -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From ashley.moran at patchspace.co.uk Sat Jul 31 03:50:40 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sat, 31 Jul 2010 08:50:40 +0100 Subject: [rspec-users] rspec 1 - nested examples (in an each block) use the final block variable 4 times instead of each of the 4 once In-Reply-To: <4d9de73c-43d5-456a-8c03-eb9b9686b771@m1g2000yqo.googlegroups.com> References: <815FC805-4DA8-46CB-853B-CC0BAE42B112@gmail.com> <9bf16ddf-7e76-4c0c-8f19-a2a11858f37b@g35g2000yqa.googlegroups.com> <3B1DAA13-21E2-4022-AF9F-6BF5C791DFD7@patchspace.co.uk> <4d9de73c-43d5-456a-8c03-eb9b9686b771@m1g2000yqo.googlegroups.com> Message-ID: <5C3419F3-7CB9-4B1F-9AC7-E6842323C1CF@patchspace.co.uk> On 31 Jul 2010, at 2:08 AM, nruth wrote: > Re: error / warning message, at the same scope (i.e. an accident, as > in the op) then yes that could be quite useful for spotting mistakes. > I'm not so sure about in different blocks though, it's probably > intentional there (different context). I forgot to add: David - think it's worth one or other of us filing a ticket for this? Is this check something that is likely to make it into RSpec? -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From ashley.moran at patchspace.co.uk Sat Jul 31 03:56:03 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sat, 31 Jul 2010 08:56:03 +0100 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <621BAF47-4CEC-4364-B706-6DFF7C9155A1@gmail.com> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> <2A82081A-ED3E-423B-A068-3FB067F8C4B6@gmail.com> <81E33C70-68CD-4415-BC9E-23D0F2B6F0FB@patchspace.co.uk> <621BAF47-4CEC-4364-B706-6DFF7C9155A1@gmail.com> Message-ID: <529E5DDF-1E2C-4F38-9DD4-DAD1350218FF@patchspace.co.uk> On 31 Jul 2010, at 1:10 AM, David Chelimsky wrote: > You can still get the same outcome, but you have to implement it in the group like this: > > unless defined?(:foo) > def foo; "foo"; end > end Maybe a DSL method while I'm working on it? Maybe: default_helper(:foo) do "foo" end WDYT? > I think it's a good trade-off to put that burden on the group (and it's author) rather that the consumers of the group. Agreed, it'd cause a lot of duplication of effort the other way round. -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From myron.marston at gmail.com Sat Jul 31 14:06:47 2010 From: myron.marston at gmail.com (Myron Marston) Date: Sat, 31 Jul 2010 11:06:47 -0700 (PDT) Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <529E5DDF-1E2C-4F38-9DD4-DAD1350218FF@patchspace.co.uk> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> <2A82081A-ED3E-423B-A068-3FB067F8C4B6@gmail.com> <81E33C70-68CD-4415-BC9E-23D0F2B6F0FB@patchspace.co.uk> <621BAF47-4CEC-4364-B706-6DFF7C9155A1@gmail.com> <529E5DDF-1E2C-4F38-9DD4-DAD1350218FF@patchspace.co.uk> Message-ID: <4977696a-94a3-4467-9048-7c8845731a52@x18g2000pro.googlegroups.com> > You can still get the same outcome, but you have to implement it in the group like this: > unless defined?(:foo) > def foo; "foo"; end > end Good point--I hadn't thought of that. The one issue I see with it is that the author of the shared example group may not have knowledge of which helper methods consumers will need to override. So he/she either defines all helper methods that way, or guesses about which ones to define that way (and potentially guesses wrong). > Maybe a DSL method while I'm working on it? ?Maybe: > > ? default_helper(:foo) do > ? ? "foo" > ? end > > WDYT? If we go the route of having the customization block evaluated first, then I like the idea, but I'm generally wary of adding more DSL methods to RSpec. I think we should be careful to only add new DSL methods that many people will find useful. If you find it useful, it's very easy to use it in your project without it being part of RSpec: just define default_helper in a module, and use config.extend YourModule in the RSpec.configuration block. (Note that I'm _not_ against adding this to RSpec: I just want to be sure we don't add a bunch of DSL methods that have limited usefulness.) Looking back at the initial example that prompted the thread, it looks to me like the primary use case for evaluating the customization block first is so that you can parameterize the shared example group's example descriptions. (There may be other use cases for defining a class-level helper methods, but none springs to mind). I also do this frequently. Often times I have something like this: [:foo, :bar, :baz].each do |method| it "does something for #{method}" do subject.send(method).should ... end end In this case I'm using the method parameter at the class level (to interpolate into the description string) and at the instance level (within the example itself). If we evaluated the customization block first, it would allow this, but you'd have to define both an instance and class helper: it_should_behave_like "something" do def self.method_name; :foo; end def method_name; :foo; end end I think this is a clunky way to essentially pass a parameter to the shared example group. Better would be something like this: it_should_behave_like "something" do providing :method_name, :foo end The instance of the shared example group provides :foo as the value of the method_name parameter. providing simply defines a class and an instance helper method with the given value. I've written up an untested gist with a start for the code that would implement this: http://gist.github.com/502409 I think there's value in evaluating the customization block first and value in evaluating it last. We can get the best of both worlds if we limit what's evaluated first to a subset (say, a few DSL methods, and maybe all class method definitions), extract it, and evaluate that first, then evaluate the shared block first, then evaluate the customization block. The gist demonstrates this as well. This may confuse people, but it does give us the best of both worlds, I think. Myron On Jul 31, 12:56?am, Ashley Moran wrote: > On 31 Jul 2010, at 1:10 AM, David Chelimsky wrote: > > > You can still get the same outcome, but you have to implement it in the group like this: > > > unless defined?(:foo) > > ?def foo; "foo"; end > > end > > Maybe a DSL method while I'm working on it? ?Maybe: > > ? default_helper(:foo) do > ? ? "foo" > ? end > > WDYT? > > > I think it's a good trade-off to put that burden on the group (and it's author) rather that the consumers of the group. > > Agreed, it'd cause a lot of duplication of effort the other way round. > > --http://www.patchspace.co.uk/http://www.linkedin.com/in/ashleymoran > > _______________________________________________ > rspec-users mailing list > rspec-us... at rubyforge.orghttp://rubyforge.org/mailman/listinfo/rspec-users From ashley.moran at patchspace.co.uk Sat Jul 31 15:42:18 2010 From: ashley.moran at patchspace.co.uk (Ashley Moran) Date: Sat, 31 Jul 2010 20:42:18 +0100 Subject: [rspec-users] Evaluating shared example customisation block before shared block In-Reply-To: <4977696a-94a3-4467-9048-7c8845731a52@x18g2000pro.googlegroups.com> References: <30EC00AE-9668-48DC-9861-E234B7D87302@patchspace.co.uk> <09CFF5F4-E1F8-417E-9781-C264B44F8081@gmail.com> <92EF66E4-3748-462D-BC85-EEF0BF51C223@patchspace.co.uk> <2A82081A-ED3E-423B-A068-3FB067F8C4B6@gmail.com> <81E33C70-68CD-4415-BC9E-23D0F2B6F0FB@patchspace.co.uk> <621BAF47-4CEC-4364-B706-6DFF7C9155A1@gmail.com> <529E5DDF-1E2C-4F38-9DD4-DAD1350218FF@patchspace.co.uk> <4977696a-94a3-4467-9048-7c8845731a52@x18g2000pro.googlegroups.com> Message-ID: <0917B197-69BE-423D-B7A8-432E796D728B@patchspace.co.uk> On 31 Jul 2010, at 7:06 PM, Myron Marston wrote: > Good point--I hadn't thought of that. The one issue I see with it is > that the author of the shared example group may not have knowledge of > which helper methods consumers will need to override. So he/she > either defines all helper methods that way, or guesses about which > ones to define that way (and potentially guesses wrong). I wonder if this will happen in practice? I can't think of an example off the top of my head, which isn't to say it won't matter, but it may be better done pull-based, when the need arises. > If we go the route of having the customization block evaluated first, > then I like the idea, but I'm generally wary of adding more DSL > methods to RSpec. I think we should be careful to only add new DSL > methods that many people will find useful. If you find it useful, > it's very easy to use it in your project without it being part of > RSpec: just define default_helper in a module, and use config.extend > YourModule in the RSpec.configuration block. (Note that I'm _not_ > against adding this to RSpec: I just want to be sure we don't add a > bunch of DSL methods that have limited usefulness.) This is a fair point. I'm going to the effort of implementing this spike in rspec-core itself because I *really* want to see if there is value in re-usable shared examples (my own, admittedly small, side-project already suggests there is). But I'm fairly sure it's not a pattern in wide use, at least not with Ruby testing libraries. > Looking back at the initial example that prompted the thread, it looks > to me like the primary use case for evaluating the customization block > first is so that you can parameterize the shared example group's > example descriptions. (There may be other use cases for defining a > class-level helper methods, but none springs to mind). I also do this > frequently. Often times I have something like this: > > [:foo, :bar, :baz].each do |method| > it "does something for #{method}" do > subject.send(method).should ... > end > end > > In this case I'm using the method parameter at the class level (to > interpolate into the description string) and at the instance level > (within the example itself). > > If we evaluated the customization block first, it would allow this, > but you'd have to define both an instance and class helper: > > it_should_behave_like "something" do > def self.method_name; :foo; end > def method_name; :foo; end > end > > I think this is a clunky way to essentially pass a parameter to the > shared example group. Funny you mention this. While I've been working on my patch[1] I came to the same conclusion. This (heavily trimmed down - I may have broken it cutting bits out for email purposes) example demonstrates it: module RSpec::Core describe SharedExampleGroup::Requirements do it "lets you specify requirements for shared example groups" do shared_examples_for("thing") do require_class_method :configuration_class_method, "message" it "lets you access #{configuration_class_method}s" do self.class.configuration_class_method.should eq "configuration_class_method" end it "lets you access #{configuration_class_method}s" do configuration_class_method.should eq "configuration_class_method" end end group = ExampleGroup.describe("group") do it_should_behave_like "thing" do def self.configuration_class_method "configuration_class_method" end end end group.run_all.should be_true end end end However, I found a serious issue with class methods, namely that they are being defined in a persistent class, not a transient ExampleGroup subclass. I haven't investigated this yet*, but I've left a pending spec at the appropriate point. * Random thought after seeing your code: using `class << self; end` over `def self.x; end` may be a partial answer? > Better would be something like this: > > it_should_behave_like "something" do > providing :method_name, :foo > end > > The instance of the shared example group provides :foo as the value of > the method_name parameter. providing simply defines a class and an > instance helper method with the given value. > > I've written up an untested gist with a start for the code that would > implement this: > > http://gist.github.com/502409 Thanks for writing this - it's an interesting piece of code. Certainly it also gets around the class/instance scope divide. But I don't think it can enforce that the parameter is provided? One of my hopes is to make the errors completely self documenting. Aside: one design decision I've made is to make every error due to a missing requirement fail at the example level, rather than abort the whole spec run. This is because RSpec-formatted requirements are MUCH easier to read than a random stacktrace in a terminal. To do this, you need to specify the class method requirement (comments added for explanatory purposes): def require_class_method(name, description) if respond_to?(name) # We have the class method, so alias it in the instance scope define_method(name) do |*args| self.class.send(name, *args) end else # We don't have the class method, so fail all the examples, # but provide a class-level method so the example definitions # doesn't fail, and break the run before(:each) do raise ArgumentError.new( %'Shared example group requires class method :#{name} (#{description})' ) end self.class.class_eval do define_method(name) do |*args| %'' end end end end > I think there's value in evaluating the customization block first and > value in evaluating it last. We can get the best of both worlds if we > limit what's evaluated first to a subset (say, a few DSL methods, and > maybe all class method definitions), extract it, and evaluate that > first, then evaluate the shared block first, then evaluate the > customization block. The gist demonstrates this as well. This may > confuse people, but it does give us the best of both worlds, I think. I think it's fair to say this is not a simple one to resolve :) Maybe David has ideas on how to reconcile everything? Cheers Ash [1] http://github.com/ashleymoran/rspec-core/tree/issue_99_shared_example_block_ordering -- http://www.patchspace.co.uk/ http://www.linkedin.com/in/ashleymoran From logiclab.co.uk at googlemail.com Fri Jul 30 12:14:25 2010 From: logiclab.co.uk at googlemail.com (S Bennett) Date: Fri, 30 Jul 2010 09:14:25 -0700 (PDT) Subject: [rspec-users] Specifying which spec types helper modules get included into in the RSpec.configure block Message-ID: <6e2e4c8f-f7cc-450e-a150-a20da2bb81f1@l14g2000yql.googlegroups.com> Hi folks, Using Rails 3.0.0.rc & RSpec 2.0.0.beta.19 I'm trying to specify what type of specs helper modules get included into such as below: config.include Devise::TestHelpers, :type => :controller When I run the controller specs I get undefined method 'sign_in' which tells me that the helpers aren't getting included. If I remove the :type => :controller hash from the statement, the module is included ok (into all spec types) and the specs pass. Am I doing something wrong or has the syntax for specifying which spec types the modules get included into changed? Thanks Simon