leifg
leifg

Reputation: 8988

Tesing Phoenix Controllers but skip Plugs

I am currently trying to test controllers in a Phoenix project.

I have a rather sophisticated authentication plug (which I test separately). I don't want to provide valid credentials for all controller tests.

Is there a way to skip certain plugs when running a test.

I experimented with bypass_through(conn, MyAppWeb.Router, []) but that doesn't seem to hit the controller function at all.

Upvotes: 1

Views: 981

Answers (2)

zwippie
zwippie

Reputation: 15515

One trick to bypass authentication logic in tests, is to directly assign attributes to the connection.

For example: a lot of authentication libraries expect a current_user to be assigned to the connection. This can be faked in the specs by just assigning the user, without any real authorization.

So, if your plug checks if a certain conn.assign is present, you can easily fake that in your tests.

An example of a controller test with some setup to do a fake login:

setup [:create_user, :login_as_registered_user]

def create_user(_) do
  user = MyApp.insert_user(%{name: "...", email: "..."})
  {:ok, user: user}
end

def login_as_registered_user(%{conn: conn, user: user}) do
  conn = Plug.Conn.assign(:current_user, user)
  {:ok, conn: conn}
end

# ...Lots of tests...

Upvotes: 2

cdegroot
cdegroot

Reputation: 1805

The simplest way is probably to do it in your application code:

if Mix.env != "test" do
  plug MyAuthenticationPlug
end

then during testing, your plug will not be compiled in.

Upvotes: 0

Related Questions