简体   繁体   中英

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.

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM