mardi 5 avril 2016

Testing whether or not methods inside controller actions get called in rspec. Mocks

Some context: I am trying to test whether a method gets called inside a controller's action. I am trying to log where users signup from (mobile, web, etc.).

Struggling with writing this spec for a controller. I wrote this test to ensure that a post_signup inside a controller action gets called:

describe Api::Users::FacebookConnectController do
...
  it "should log an event with an app_context" do
        expect_any_instance_of(described_class).to receive(:post_signup)

        subject
  end

It is quick and dirty and doesn’t even check to see which arguments the method #post_signup gets called with.

My actual controller has a #register method that at some point calls this post_signup method:

  post_signup(user,
            Event::EventType::USER_FB_ACCOUNT_NON_SUBSCRIPTION_COMPLETED,
            app_context: current_app_id,
            description: "Automatically Populated Via #{current_app_id}")

The post_signup method inside a helper that gets included in the controller looks like this:

def post_signup(user, event_type, app_context: current_app_id, description: "Automatically populated")
...
      Event.create!(
        event_type: event_type,
        date: Time.now.utc,
        eventable: user,
        description: description,
        app_context: app_context
      )
...
end

So in short, this seems like a reasonable thing for me to test. I want to test that #post_signup gets called when the #register action gets called int the controller

My test sucks I feel because I’m not actually capturing the actual controller. I’m testing that ANY instance of a controller receives the post_Signup method and I’m also not specifying arguments. How do I do this with a mock? How do I test the actual controller that's in the described class and not just some random instance? How do I check to see if post_signup is called with an argument called app_context?

Aucun commentaire:

Enregistrer un commentaire