EzDevInfo.com

rr

RR (Double Ruby) is a test double framework that features a rich selection of double techniques and a terse syntax. rr/rr · GitHub rr - rr is a test double framework that features a rich selection of double techniques and a terse syntax.

How to call original method in btakita/rr ?

I need to check that particular method is called. Is it possible in btakita/rr?

rspec example from: https://www.relishapp.com/rspec/rspec-mocks/v/2-13/docs/message-expectations/calling-the-original-method!

    Addition.should_receive(:two_plus_two).and_call_original

Source: (StackOverflow)

What is the best practice when it comes to testing "infinite loops"?

My basic logic is to have an infinite loop running somewhere and test it as best as possible. The reason for having an infinite loop is not important (main loop for games, daemon-like logic...) and I'm more asking about best practices regarding a situation like that.

Let's take this code for example:

module Blah
  extend self

  def run
     some_initializer_method
     loop do
        some_other_method
        yet_another_method
     end
  end
end

I want to test the method Blah.run using Rspec (also I use RR, but plain rspec would be an acceptable answer).

I figure the best way to do it would be to decompose a bit more, like separating the loop into another method or something:

module Blah
  extend self

  def run
     some_initializer_method
     do_some_looping
  end

 def do_some_looping
   loop do
     some_other_method
     yet_another_method
   end
 end
end

... this allows us to test run and mock the loop... but at some point the code inside the loop needs to be tested.

So what would you do in such a situation?

Simply not testing this logic, meaning test some_other_method & yet_another_method but not do_some_looping ?

Have the loop break at some point via a mock?

... something else?


Source: (StackOverflow)

Advertisements

Unit Testing Ruby Blocks by Mocking with rr (was flexmock)

How do I unit test the following:

  def update_config
    store = YAML::Store.new('config.yaml')
    store.transaction do
      store['A'] = 'a'
    end
  end

Here is my start:

  def test_yaml_store
    mock_store = flexmock('store')
    mock_store
      .should_receive(:transaction)
      .once
    flexmock(YAML::Store).should_receive(:new).returns(mock_store)
    update_config()
  end

How do I test what is inside the block?

UPDATED

I have converted my test to spec and switched to rr mocking framework:

describe 'update_config' do
  it 'calls transaction' do
    stub(YAML::Store).new do |store|
      mock(store).transaction
    end
    update_config
  end
end

This will test the transaction was called. How do I test inside the block: store['A'] = 'a'?


Source: (StackOverflow)

Stub (...) received unexpected message (...) with (no args)

I try to write a test using RR. What I need is a stub of a model object.

describe ApplicationController do

  subject(:application_controller)     { ApplicationController.new }
  let(:messages)                       { ['a1', 'a2', 'a3' ] }
  let(:model)                          { Object.new }

  it 'should copy errors to flash' do
    stub(model).error_messages { messages }
    flash[:error] == nil
    subject.copy_errors_to_flash(model)
    flash[:error].should == messages
  end

end

What I get is

ApplicationController should copy errors to flash
     Failure/Error: stub(model).error_messages { messages }
       Stub #<Object:0x007ffaa803f930> received unexpected message :error_messages with (no args)
     # ./spec/controllers/application_controller_spec.rb:10:in `block (2 levels) in <top (required)>'

I have no idea what am I doing wrong. I think I follow the docs...


Source: (StackOverflow)

Unit Testing updating a mongoid field using rr

I am trying to unit test the following code:

require 'mongoid'

class Seller
  include Mongoid::Document

  field :updated_at, type: Time

  def update_updated_at
    updated_at = Time.now
    save
  end

end

Here is my attempt

describe Seller do

  describe 'update_updated_at' do

    it 'sets updated_at to Time.now' do
      now = Time.new(2013,10,14)
      seller = Seller.new
      mock(Time).now { now }
      mock(seller).updated_at= now
      mock(seller).save
      seller.update_updated_at
    end

  end

end

I am getting the following failure

updated_at=(2013-10-14 00:00:00 -0600)
Called 0 times.
Expected 1 times.

Source: (StackOverflow)

How do I create and assign a stub object using RR?

I am trying the RR double framework for the first time and am a bit stuck on how to convert my existing RSpec stubs. I see how I can use double graphs in the documentation for the same result as RSpec's stub_chain, but how do create a stub/mock that just responds to defined methods?

For instance, in RSpec, I could do admin = stub(admin?: true) and then use admin. Can I do this in RR, without having to first have admin defined? admin = User.new; stub(admin).admin? { true }

I was able to do something like admin = stub; stub(admin).admin? { true }, but that double stub seems odd.


Source: (StackOverflow)

Mocking Validates Uniqueness Callback

How do you mock out the validates :name, uniqueness: true callback for an attribute?

I imagine it would work something like this:

describe "with duplicate name" do
  before { mock(subject.name).unique? { false } }

  it "should be invalid" do
    subject.should have(1).error_on(:name)
  end

Source: (StackOverflow)

DNS Resource Record Type Field (MB, MG, MR)

What is usage of MB, MG, MR types in a Resource Record?

Some information in Here, but I can't understand their usage in real world!


Source: (StackOverflow)

How do I write a spec to verify the rendering of partials?

I'm using rr (the mocking framework) and rspec with ruby-on-rails. Also, I'm using the collection short hand for partial rendering. My question: How do I correctly fill out the the following view spec?

describe 'my_view' do
  before(:each) do
    assigns[:models] = Array.new(10, stub(Model))
  end

  it "should render the 'listing' partial for each model" do
    # help me write something that actually verifies this
  end
end

I've tried a few examples from the rspec book, rspec docs, and rr docs. Everything I try seems to leave me with runtime errors in the test - not failed assertions. Rather than show all the transformations I've tried, I figured all I'd need if someone showed me one that actually worked. I'd be good to go from there.


Source: (StackOverflow)

yield to a block using rr

I'm trying to test the following code using rr:

response = RestClient.get(url, {:params => params}){|response, request, result| response }

In vanilla rspec, you would do something like this:

RestClient.should_receive(:get).with(url, {:params => params}).and_yield(response, request, result)

How would I do the same with rr?

Setup:

let(:url) { "http://localhost/" }
let(:params) { {:item_id => 1234, :n => 5} }
let(:response) { Object.new }
let(:request) { Object.new }
let(:result) { Object.new }

I've tried a bunch of variations on:

mock(RestClient).get(url, {:params => params}) { response, request, result }

and

mock(RestClient).get(url, {:params => params}, &proc/lambda{}).return(result)

and

mock(RestClient).get(url, {:params => params}).yields(response, request, result)

and

mock(RestClient).get(url, {:params => params}).returns do |proc_as_block|
  response
end

but none of them work.


Source: (StackOverflow)

Java ArrayList in ArrayList

I have a question about an ArrayList inside an Arraylist. It's about multiple worlds with multiple spawns. I want to check every world one by one and save all the spawns of that world in an ArrayList. At the end I have an ArrayList with on every position (every position is a world) another Arraylist containing the spawns of that world.

How can I do this if I don't know how many spawns or worlds there are going to be? I thought of this:

Looking to just one world:

public ArrayList<Location> Spawnpoints = new ArrayList<Location>(); 
//ArrayList containing all the spawns of this world).

Looking to every single spawn in the world

 Spawnpoints.add(new Location(spawnX , spawnY , spawnZ)); 
//Adding every spawn to the ArrayList spawnpoints.

So after I looked at a world I have filled the ArrayList spawnpoints with locations. Now I want to add the ArrayList spawnpoints to a new ArrayList worlds. After that I will repeat the code above for the next world, untill I have had all the worlds.

EDIT. I think it's working. I have troubles with getting the size of the list when I only have the name.

So let's say I did this: allSpawnpoints.put("yourWorld",Spawnpoints); Now I want to get the size of the Spawnpoints list for the string yourWorld. Any idea how I can do this?

I tried: int number = allSpawnpoints.get("yourWorld").size(); it looks like that isn't working.

I hope someone can help me! Thanks for reading. Regards.


Source: (StackOverflow)

RSpec view test using RR failing - undefined method stub

I am using Rails 3.1, RSpec 2.6, and rr 1.0.4 and I get a NoMethodError:

undefined method `stub' for #<Activity:0x007faa90996190>

I am trying to utilize the RSpec test below to test my "Activities" show.haml view. If I change my spec_helper.rb file to use RSpec for mocks instead of rr then the test passes. I have tried changing the syntax of the code but to no success.

I found several websites stating that RSpec and rr do not "play well together and one person provided this rpsec-rr solution which did not work for me.

This is my show.haml_spec.rb

require 'spec_helper'

describe "activities/show.haml" do
  before(:each) do
    @activity = assign(:activity, stub_model(Activity))
  end

  it "renders attributes in .haml" do
    render
  end
end

This is the output from my Eclipse compiler using Aptana Studio

Failures:

  1) activities/show.haml renders attributes in .haml
     Failure/Error: @activity = assign(:activity, stub_model(Activity))
     NoMethodError:
       undefined method `stub' for #<Activity:0x007faa90996190>
     # ./spec/views/activities/show.haml_spec.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.15479 seconds
1 example, 1 failure

Failed examples:
rspec ./spec/views/activities/show.haml_spec.rb:8 # activities/show.haml renders attributes in .haml

Any recommendation to an alternate syntax would be greatly appreciated!!


Source: (StackOverflow)

Rspec actions that change the DB

I'm a bit confused with the behavior of rpsec tests involving controller methods that affect the DB. I have seen many examples of rspec tests that involve POST's and DELETE's where people check to see that an object was created or deleted. In most of these tests people are able to just check that the count of the model in the DB has increased or descreased with a tests such as:

delete :clear_photos, :id => @album.id
@album.photos.size.should == 0 

or with lambdas:

lambda {delete :destroy, :id => @photo.id}.should change(@album.photos, :size).by(-1)

The syntax isn't perfect in the last example but my point is that in my experience, I have needed to call reload on the object in order for any of these tests to pass, but for some reason, other are able to make them work without explicitly calling reload. Something about calling reload every time I am testing a db create/destroy action seems fishy to me.

Can anyone help me understand what's going on? Thanks!

ACTUAL CODE UPDATE

it "should clear all photos for an album" do
  @album = Factory(:album, :photos => [Factory(:photo), Factory(:photo)])
  delete :clear, :album_id => @album.id
  @album.photo_count.should == 0
end

I get this response:

'PhotosController#clear should clear all photos for an album' FAILED
expected: 0,
     got: 2 (using ==)
./spec/controllers/photos_controller_spec.rb:17:

If I reload the @album before calling photo_count though, it works.


Source: (StackOverflow)

How do you mock a method with a block using RR (double ruby) on Rails 3

I am using the Koala gem to make facebook requests and i have the following code:

  @graph = Koala::Facebook::API.new(oauth_token)
  @graph.batch do |batch_api|
    #... do stuff here
  end

I want to mock out the batch call to simulate the stuff we are doing in there.

Here is what i have in RR.

oauth_token= "Sometoken"
batch_api_mock = nil
graph_mock = mock(Koala::Facebook::API).new(oauth_token).mock!
graph_mock.batch.returns do
  yield batch_api_mock if block_given?
end

The problem is that block_given? is return false even though there is a block being passed in my source.

How do i mock a method that takes a block using RR?


Source: (StackOverflow)

mocking in Ruby: mocks are sticking around between tests

I'm using RR as the mocking framework for a personal project of mine. I've been using it to mock the new method for some classes and when I run the tests they pass fine, but when I run ALL of the tests I run into a problem where it seems like the "new" methods are still returning the fake results, even when in a different test file. Is there a way to turn off the stubbing of the new method manually? What am I missing here?

Thanks for the help, Alex

I've tried putting this code into my app and it breaks the app, and.... doesn't fix the above problem.

RSpec.configure do |config|
  config.mock_with :rr
end

Source: (StackOverflow)