mirror of
https://github.com/thoughtbot/shoulda-matchers.git
synced 2022-11-09 12:01:38 -05:00
c683aed2f0
When specifying a custom subject, a straightforward usage of `delegate_method`, such as the following class UserPresenter delegate :id, to: :user attr_reader :user def initialize(user) @user = user end end class UserPresenterTest < ActiveSupport::TestCase subject { UserPresenter.new(User.new) } should delegate_method(:id).to(:user) end would error with something like: ArgumentError: wrong number of arguments (0 for 1) This happens because the `should` method in shoulda-context asks the DelegateMethodMatcher object for its description so that it can use it to give the test a name and create a method that Test::Unit can run. Now, the matcher's description needs a subject in order to determine whether a class or an instance is being tested here -- if a class is being tested the description will be "should delegate #id to \#user object", if a class then "should delegate .id to .user object". Unfortunately the matcher doesn't know what the subject is before its #description method is called -- it only knows about this when it gets evaluated. Within the matcher we do have access to the current context class, so we could read the subject block off of it and evaluate it. However, in order to properly do this we also need access to the instance of the test itself, which we do not have until the matcher is evaluated (by which point it's too late). Since there's really no way to solve this problem apart from rewriting a lot of shoulda-context, and since often times your subject is an instance and not a class, just assume it's an instance in this case.
47 lines
1.3 KiB
Gherkin
47 lines
1.3 KiB
Gherkin
Feature: Independent matchers
|
|
Background:
|
|
When I generate a new Ruby application
|
|
|
|
Scenario: A Ruby application that uses Minitest and the delegate_method matcher
|
|
When I add Minitest to the project
|
|
And I write to "lib/post_office.rb" with:
|
|
"""
|
|
class PostOffice
|
|
end
|
|
"""
|
|
And I write to "lib/courier.rb" with:
|
|
"""
|
|
require "forwardable"
|
|
|
|
class Courier
|
|
extend Forwardable
|
|
|
|
def_delegators :post_office, :deliver
|
|
|
|
attr_reader :post_office
|
|
|
|
def initialize(post_office)
|
|
@post_office = post_office
|
|
end
|
|
end
|
|
"""
|
|
And I write a Minitest test to "test/courier_test.rb" with:
|
|
"""
|
|
require "test_helper"
|
|
require "courier"
|
|
require "post_office"
|
|
|
|
class CourierTest < {{MINITEST_TEST_CASE_CLASS}}
|
|
subject { Courier.new(post_office) }
|
|
|
|
should delegate_method(:deliver).to(:post_office)
|
|
|
|
def post_office
|
|
PostOffice.new
|
|
end
|
|
end
|
|
"""
|
|
And I set the "TESTOPTS" environment variable to "-v"
|
|
And I successfully run `bundle exec ruby -I lib -I test test/courier_test.rb`
|
|
Then the output should indicate that 1 test was run
|
|
And the output should contain "Courier should delegate #deliver to #post_office object"
|