On Mon, Dec 3, 2012 at 2:33 PM, David Chelimsky <[email protected]> wrote:
> On Mon, Dec 3, 2012 at 2:10 PM, Chris Bloom <[email protected]> wrote:
>> I'm trying to refactor some common code used in a bunch of requests specs
>> into a macro, but every way I've tried so far ends in an error saying it
>> can't find the macro method, or if it can then it can't find the `get`
>> method. Can someone point me to an example of how to do this?
>>
>> # spec/requests/api/api_v1.rb
>> describe MyApp::API_v1 do
>>   context "originator" do
>>     describe "GET /api/v1/originator/hello" do
>>       it_should_check_minimum_protected_api_params
>> "/api/v1/originator/hello"
>>     end
>>   end
>> end
>>
>> # spec/support/api_macros.rb
>> module ApiMacros
>>   def self.included(base)
>>     base.extend(GroupMethods)
>>   end
>>
>>   module GroupMethods
>>     def it_should_check_minimum_protected_api_params(url)
>>       get url
>>       ...
>>     end
>>   end
>> end
>>
>> # spec/spec_helper.rb
>> RSpec.configure do |config|
>>   config.include ApiMacros, :type => :request
>> end
>>
>> This ends in:
>>
>> $ rspec spec/requests/api
>> /spec/support/api_macros.rb:8:in
>> `it_should_check_minimum_protected_api_params': undefined method `get' for
>> #<Class:0x000001036708f0> (NoMethodError)
>
> That's not saying it can't find the macro method. It says it can't find `get`.
>
> The macro is being evaluated at the class level, whereas "get" is an
> instance method. The macro needs to define examples that use the get
> method, e.g:
>
> def it_should_check_minimum_protected_api_params(url)
>   it "should check minimum protected api params" do
>     get url
>     # ...
>   end
> end
>
> HTH,
> David

BTW - another approach is to write a matcher and use the one-liner syntax:

RSpec::Matchers.define :check_minimum_protected_api_params do |url|
  match do |_|
    get url
    # .... return true/false for pass/fail
  end
end

Now you can say:

  it { should check_minimum_protected_api_params("/api/v1/originator/hello") }

Cheers,
David

-- 
You received this message because you are subscribed to the Google Groups 
"rspec" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to