Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

Dmitriy Kalinin

Posts By

PIVOTAL LABS
[standup] [sf] 03/27/13: Metro DC

Helps Sinatra Logger

We have a Sinatra app mounted on Rails. If we raise an error in the Sinatra app, it doesn’t show anywhere. Can we attach the Rails logger somehow?

Interestings Code Climate Blog: Rails Insecure Defaults

http://blog.codeclimate.com/blog/2013/03/27/rails-insecure-defaults/

Rubymine 5.4 EAP: Rails 4, JRuby Nailgun support, and a feature requested by pivotallabs!

Read more »

PIVOTAL LABS
[standup] [sf] 03/25/13: Zvezdochka

Interestings .ruby-version (& .ruby-gemset)

The community appears to be converging on .ruby-version as a standard way to convey a project’s Ruby version. This as opposed to .rvmrc or .rbenv

If you use RVM you can also use .ruby-gemset to specify a gemset.

Read more »

PIVOTAL LABS
June 1st, 2012: National Donut Day

Helps

  • Sprockets fail in CI, not locally?

No answer.

Interestings

  • capybara-webkit has non-standard awesomeness

https://github.com/thoughtbot/capybara-webkit#non-standard-driver-methods

Things like:

  • driver.resize_window
  • driver.console_messages
  • driver.render to get an image of the viewport. inorite?

PIVOTAL LABS
Standup May 31st, 2012: Thursday

Interestings

  • RVM now supports custom SSL versions

Our project needs OpenSSL > v1.0.0 because we're trying to sign something with a DSA key. We asked on github and fifteen minutes later mpapis had pushed a change to make it configurable. That's some of the best open source service out there.

  • Chrome Heap inspector is your friend
  • Backbone Events do NOT get cleaned up

If you declare any events in the events property of a initialize, they prevent your instance from being deleted/GC'd. Use an explicit destroy function that calls this.undelegateEvents()

LABS
without_page_refresh capybara helper

I recently had to write a small capybara helper:

def without_page_refresh
  page.execute_script("window._withoutPageRefresh = 'BAM'")
  yield
  page.evaluate_script("window._withoutPageRefresh").should == "BAM", "Page was navigated away"
end

Use case:

You are building a form that gracefully degrades when javascript is not enabled. It goes something like this:

# uses rack-test so no javascript
scenario "User can lose money in an accessible way" do
  visit "/your_account"
  page.should have_content "You have $100"
  click_button "Charge me"
  page.should have_content "You have $50"
end

Next step is to make that form do the ajax thingy. You copy test above and switch it to use javascript driver:

# uses selenium for javascript
scenario "User can lose money with style", :js => true do
  visit "/your_account"
  page.should have_content "You have $100"
  click_button "Charge me"
  page.should have_content "You have $50"
end

Newly written test is pretty good except that it passes without writing a single line of javascript. So here's when that helper comes into play. Our javascript test becomes:

# uses selenium for javascript
scenario "User can lose money with style", :js => true do
  visit "/your_account"

  without_page_refresh do
    page.should have_content "You have $100"
    click_button "Charge me"
    page.should have_content "You have $50"
  end
end

Now javascript test fails with "Page was navigated away" since nothing is preventing that form from submiting to another page.

PIVOTAL LABS
SF Standup for Friday, 12/9/2011

Ask for Help

  • RubyMine 3.2.4 is slow... Solution is to update to the latest RubyMine EAP 4.

Interesting Things

  • Yehuda Katz announces Amber.js (previously known as SproutCore 2.0). "Amber brings a proven MVC architecture to web applications, as well as features that eliminate common boilerplate. If you played with SproutCore and liked the concepts but felt like it was too heavy, give Amber a try." -YK

  • Updates in active_admin silently fail if you are using it with inherited_resources 1.3.0. Use 1.2.2 instead.

LABS
Cedar and OCUnit

tl;dr Latest version of Cedar can nicely integrate with Xcode just like OCUnit.

Why

When creating new Xcode project you might have noticed that New Project dialog has 'Include Unit Tests' checkbox at the bottom. When that option is selected in addition to creating an app target Xcode will also create a separate target that is used for testing your application. This target most likely will be named [app]Tests. Convenient, huh! Since Xcode is such a nice IDE[1] it will also create an example test file that uses Xcode's built-in unit testing framework -- OCUnit (also known as SenTestingKit). If you never heard of it below is a screenshot of how that example OCUnit test file looks.

Because Apple ships OCUnit with Xcode it is tightly integrated into the IDE and that gives it somewhat of an advantage over other testing frameworks. Example of such unfair treatment is relatively nice looking red error markers (shown above) that show up next to failed test cases when application tests are run. If you have ever used Cedar before you would know that when Cedar specs fail we do not get those markers but rather we are presented with boring gray console output (we have dots though!). Unfortunately there is no documented way for custom testing frameworks to mimic OCUnit behavior without building on top of it. But even if do decide to use OCUnit as a base for your custom testing framework you will run into several problems. One of those problems, at least a year ago, was that you could not reliably use debugger with OCUnit tests. That was one of the main reasons why Cedar was not build on top of it. Recently, however, Xcode 4 was released with a lot of enhancements including better support for running OCUnit tests (with or without debugger) or so it seems. Red markers being a driving force, once again it was worth to investigate on how take advantage of OCUnit goodies from Cedar. Latest version of Cedar succeeds at that. What follows are the steps on how to setup Cedar for maximum Xcode integration.

Setup steps

Check 'Include Unit Tests' checkbox in New Project dialog. If you want to add application tests to an existing project here is a very nice tutorial: http://twobitlabs.com/2011/06/adding-ocunit-to-an-existing-ios-project-with-xcode-4/

After Xcode is done creating a new project file go to Build Settings for application tests target (in this case ExampleTests) and find Other Linker Flags settings. Add -ObjC, -all_load, and -lstdc++ to that setting and click Done.

Next step is to add Cedar static library to application tests target.

Now you are ready to create a Cedar spec file. Create a new empty file and end the filename with 'Spec.mm'. 'mm' file extension is needed to be able to use built-in Cedar matcher library. Also since this file should only be run as part of application tests and not the actual application make sure that you only include it in application tests target.

Add a test or two (see above for example) to be able to test that Cedar is working correctly. Example above tries to assert that 2+2 equals 5 and that should hopefully fail. Notice that here I'm using recently added Cedar matchers should syntax. If you do not like that you can always rewrite that expectation as expect(2+2).to(equal(5));

Larger image. And finally to run specs you just wrote select scheme for your app (in this case Example) from the drop down in the upper left corner and press 'Cmd+U'. 'Cmd+U' in Xcode by default runs tests associated with selected scheme. That should first build your app (because application tests target lists the app as a target dependency), then build application tests target and then run the tests. Since 2+2 does not equal 5 you will see that Xcode will highlight that line in red and show that as an error in the errors panel on the left side. Fixing that expectation should make the test pass.

Running from the command line

If you want to run your application tests from the command line you can use rake ocunit:application to do that. Before doing so make sure you have updated APP_NAME and OCUNIT_APPLICATION_SPECS_TARGET_NAME in the Rakefile. Also you'll need to use Debug for CONFIGURATION so that your tests are able to include classes from your application. What's nice about this rake task is that it is ready to be used on your CI machine since it returns exit code 1 when any tests fail and 0 if they all succeed. It also prints in color.

How it actually works

If you are wondering how Cedar pretends to be OCUnit here is a short summary:

  • When Cedar is loaded it overrides runTests class method on SenTestProbe class (related file to look at is CDROTestIPhoneRunner.m)
  • SenTestProbe +runTests gets called by otest -- an executable that Xcode uses to run tests after it injected the application tests bundle into TEST_HOST app
  • Since SenTestProbe +runTests was overridden with Cedar's run method Cedar executes all of its specs following all the usual rules: focused, pended, etc.
  • When specs are running CDROTestReporter (source) gets notified which tests passed, failed, got skipped, etc. and prints out appropriate information which you see in console log
  • CDROTestReporter prints out failed tests in a way that is recognized by Xcode (OCUnit spits out same output for failed examples) e.g.:
Test Case '-[ExampleTests testExample]' started.
/Users/work/workspace/Example/ExampleTests/ExampleTests.m:16: error: -[ExampleTests testExample] : '4' should be equal to '5': 2+2 != 5
Test Case '-[ExampleTests testExample]' failed (0.000 seconds).
  • Xcode notices that pattern in the console output, parses it, gets filename and line number and marks that file location with a red marker to indicate a test failure

Drawbacks/Not implemented features

  • Debugger support is still a bit flaky but this is a problem with Xcode/OCUnit integration
  • I have not tried running it on the device but it should work
  • If you are used to specifying -SenTest option to run specific test case it will be ignored; however, you can use Cedar's fit, fdescribe, and fcontext to focus on specific tests
  • Some third party OCUnit add-ons might not work (let us know about them)

Useful links

[1] It's not.

LABS
Too many parentheses

Cedar comes with its own built-in matcher library and here is Adam Milligan's blog post that explains on how to use it. An example of expectation written using Cedar matcher library:

expect(controller.button).to_not(be_nil());

Even though this is much better than OCHamcrest it is still not satisfying (in my opinion) because there are so many parentheses involved. Since Cedar matcher library is written in C++ we can do some magic here. The result is you can write your expectations like this:

controller.button should_not be_nil;

So let's dig into how Cedar's should syntax is implemented.

  controller.button   should_not   be_nil
|-------------------|------------|--------|
    actual value       C macro     matcher

As you might have guessed should and should_not are C macros. Besides making possible for each expectation to know its filename and line number (with __FILE__ and __LINE__ preprocessor variables), they also hide the unnecessary complexity which makes this syntax possible. Here is how it looks expanded:

  controller.button   ,(ActualValueMarker){__FILE__, __LINE__},true,   be_nil
|-------------------|------------------------------------------------|--------|
    actual value                        mumbo jumbo                    matcher

So how does this mumbo jumbo work? Since Cedar matcher library was written in C++ we can overload the comma operator. Besides being a weird operator to overload, it has a useful property that we can exploit here. Comma operator has the lowest precedence among all other operators and that allows us to write 2+2 should equal(4) instead of (2+2) should equal(4). Now let's break mumbo jumbo into pieces:

(1) <actual value>
    (ActualValueMarker){__FILE__, __LINE__} -> (2) ActualValue
                                                   true/false  -> (3) ActualValueProxy
                                                                      <matcher>

(1) This step captures actual value (can be anything since it is templated), filename and line number. It is implemented like this:

template<typename T>
const ActualValue<T> operator,(const T & actualValue, const ActualValueMarker & marker) {
    return ActualValue<T>(marker.fileName, marker.lineNumber, actualValue);
}

(2) Now we overload comma operator to match ActualValue (returned from step 1) and a bool that indicates whether matcher result should be negated.

template<typename T>
const ActualValueMatchProxy<T> operator,(const ActualValue<T> & actualValue, bool negate) {
    return negate ? actualValue.to_not : actualValue.to;
}

(3) And finally we overload comma operator again so that it matches ActualValueMatchProxy (returned from step 2) and anything else. Second argument will be considered to be a matcher.

template<typename T, typename MatcherType>
void operator,(const ActualValueMatchProxy<T> & matchProxy, const MatcherType & matcher) {
    matchProxy(matcher);
}

That's pretty much all. Full implementation of should syntax (which is just several more lines more than what is shown above) can be found in ShouldSyntax.h (and corresponding spec file that makes sure syntax works). Everything above allows us to write expectations as follows:

controller.button should_not be_nil();

Since the goal is to get rid of as many parentheses as possible we still have some work to do. Nil matcher that comes with Cedar is implemented with BeNil class. The way it worked before was be_nil was a function defined in Cedar::Matchers namespace. Calling it each time would return a new instance of BeNil class. To make parentheses go away be_nil was turned into a static variable that is initialized only once to an instance of BeNil class. (be_nil matcher still supports being used with two parentheses for backwards compatibility by implementing call operator on BeNil class.) Bam.

controller.button should_not be_nil;

Usually it is not recommended to use operator overloading for non-operator related purposes (e.g. don't use + operator for subtraction); however, in this case I think it's fine to bend the rules just a bit to escape all those parentheses and provide clean expectation DSL. You can use should syntax with the latest Cedar master branch.

PIVOTAL LABS
SF Standup for Friday, 4/29/2011: It's Friday, Friday…

Interesting Things

  • Be aware that when chaining rake tasks (e.g. rake db:migrate db:seed ...) ruby classes do not get reloaded in between tasks so you can end up with old class definitions.
  • Jared created http://hackingadvertising.com/ to record his findings about running different ads through Google Adwords and Facebook Ads.
  • Requiring cancan matchers in spec_helper.rb breaks RubyMine's ability to run specs. Same weird behavior was noticed with other gems that rely on shoulda.